接口中的Typescript函数重载`
我第一次使用Typescript中的重载,在接口中的Typescript函数重载`,typescript,overloading,Typescript,Overloading,我第一次使用Typescript中的重载,在接口中定义重载时遇到了一些错误 我认为我正确理解了这个概念,因为这些示例编译时没有错误: 函数测试():void; 功能测试(str:string):字符串; //嗯 功能测试(str?:字符串){ if(typeof str==='string')返回str; }; test();//好啊 测试(“”);//好啊 类Test2{ 公共测试():无效; 公共测试(str:string):字符串; //嗯 公共测试(str?:字符串){ if(type
接口中定义重载时遇到了一些错误
我认为我正确理解了这个概念,因为这些示例编译时没有错误:
函数测试():void;
功能测试(str:string):字符串;
//嗯
功能测试(str?:字符串){
if(typeof str==='string')返回str;
};
test();//好啊
测试(“”);//好啊
类Test2{
公共测试():无效;
公共测试(str:string):字符串;
//嗯
公共测试(str?:字符串){
if(typeof str==='string')返回str;
}
构造函数(){
this.test();//确定
this.test(“”);//好的
}
}
但是,这些都会抛出:
类型“()=>void”不能分配给类型“{():void;(str:string):string;}”。
Type'(str:string)=>string'不能分配给类型“{():void;(str:string):string;}”。
接口测试{
test():void;
测试(str:string):字符串;
}
常量test1:Test={
测试:()=>{},//错误
};
常量test2:测试={
test:(str:string)=>str,//错误
};
类测试实现测试{
构造函数(){
this.test=()=>{};//错误
this.test=(str:string)=>“”;//错误
}
}
我是做错了什么,还是这是打字脚本中的错误
编辑:下面是失败案例中的代码,因为每次分配的实现都只满足接口中定义的一个重载函数签名
这将很难做到,因为您不能在任何给定对象上定义具有相同名称的两个属性。因此,就像您的函数
声明一样,您需要提供一个满足两个函数签名的实现:
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;
}
}
}
如上所述,指定同时匹配void
和string
的返回类型非常重要(不可能?),因此需要使用any