簡體   English   中英

`interface` 中的 Typescript 函數重載

[英]Typescript function overloading in `interface`

我第一次使用 Typescript 中的重載,並且在interface定義它們時遇到了一些錯誤。

我想我正確理解了這個概念,因為這些例子編譯沒有錯誤:

function test(): void;
function test(str: string): string;

// OK
function test(str?: string) {
    if (typeof str === 'string') return str;
};

test(); // OK
test(''); // OK
class Test2 {
    public test(): void;
    public test(str: string): string;

    // OK
    public test(str?: string) {
        if (typeof str === 'string') return str;
    }

    constructor() {
        this.test(); // OK
        this.test(''); // OK
    }
}

但是,這些都拋出:

  • Type '() => void' is not assignable to type '{ (): void; (str: string): string; }'.
  • Type '(str: string) => string' is not assignable to type '{ (): void; (str: string): string; }'.
interface Test {
    test(): void;
    test(str: string): string;
}

const test1: Test = {
    test: () => {}, // ERROR
};

const test2: Test = {
    test: (str: string) => str, // ERROR
};

class Test implements Test {
    constructor() {
        this.test = () => {}; // ERROR
        this.test = (str: string) => ''; // ERROR
    }
}

我做錯了什么,還是這是 Typescript 中的錯誤?

編輯:這是Typescript Playground 中的代碼

您的失敗案例失敗了,因為在每種情況下,您都分配了一個僅滿足接口中定義的重載函數簽名之一的實現。

這很難做到,因為您不能在任何給定對象上定義兩個具有相同名稱的屬性。 因此,就像您的function聲明的情況一樣,您需要提供一種滿足兩個函數簽名的實現:

interface Test {
    test(): void;
    test(str: string): string;
}

const test: Test = {
    test: (str?: string): any => {
        if (typeof str === 'string') return str;
    }
};

class Test implements Test {
    constructor() {
        this.test = (str?: string): any => {
            if (typeof str === 'string') return str;
        }
    }
}

如前所述這里,指定同時匹配返回類型voidstring是不平凡的(不可能的?),因此需要使用any

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM