首页 > 解决方案 > `interface`中的Typescript函数重载

问题描述

我第一次在 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
    }
}

但是,这些都抛出:

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中的代码

标签: typescriptoverloading

解决方案


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

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


推荐阅读