繁体   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