我是打字稿的新手,这是一个我想要实现的界面;
interface IThing{
name:string;
age:number;
sayHello:{
(name:string):string;
(age:number):number;
}
}
sayHello 有两个签名,表示过载版本。我只是不知道如何在课堂上实现这一点,任何帮助?感谢。
答案 0 :(得分:11)
要实现重载函数,请首先编写要显示的所有重载调用签名,然后是实现签名,该签名是所有重载签名的超集。例如:
class Thing implements IThing {
// Implement the name and age fields
name: string;
age: number;
// Overload signature #1
sayHello(name: string): string;
// Overload signature #2
sayHello(age: number): number;
// Implementation signature, not visible to external callers
sayHello(arg: any): any {
if(typeof arg === 'string') {
return this.name;
} else if(typeof arg === 'number') {
return this.age;
} else {
throw new Error('sayHello can only take string or a number');
}
}
}
var x = new Thing();
var n = x.sayHello('world'); // n: string
var a = x.sayHello(42); // a: number
var e = x.sayHello(false); // error: false is not string or number