【发布时间】: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中的代码
【问题讨论】: