【问题标题】:Typescript function overloading in `interface``interface`中的Typescript函数重载
【发布时间】:2020-03-04 05:12:30
【问题描述】:

我第一次在 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中的代码

【问题讨论】:

    标签: typescript overloading


    【解决方案1】:

    您的失败案例之所以失败,是因为在任何情况下,您都分配了一个仅满足接口中定义的重载函数签名之一的实现。

    这很难做到,因为您不能在任何给定对象上定义两个具有相同名称的属性。因此,就像您的 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;
            }
        }
    }
    

    here 所述,指定与voidstring 匹配的返回类型并非易事(不可能?),因此需要使用any

    【讨论】:

      猜你喜欢
      • 2017-07-26
      • 2012-10-24
      • 2012-09-24
      • 2020-06-08
      • 1970-01-01
      • 2016-10-27
      相关资源
      最近更新 更多