如何在TypeScript接口中实现重载方法? [英] how to implement overload method in TypeScript Interface?
本文介绍了如何在TypeScript接口中实现重载方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Typescript的新手,这是我要实现的接口;
i am new to typescript, here is a interface which i'd like to implement;
interface IThing{
name:string;
age:number;
sayHello:{
(name:string):string;
(age:number):number;
}
}
sayHello 有两个签名,指示重载版本.我只是不知道如何在课堂上实现这一点,有帮助吗?谢谢.
sayHello has two signatures which indicates overload version. i just don't know how to implement that in a class, any help? thanks.
推荐答案
要实现重载功能,请首先编写要显示的所有重载调用签名,然后编写是所有重载签名的超集的实现签名..示例:
To implement an overloaded function, write all the overload call signatures you want to be visible first, followed by an implementation signature that is a superset of all the overload signatures. Example:
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
这篇关于如何在TypeScript接口中实现重载方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文