我搜索了所有可能的方法,但我无法弄清楚如何组合返回类型注释和胖箭头语法.
class BasicCalculator{
value:number;
constructor(value:number=0){
this.value=value;
}
add= (operand:number)=>{ // CAVEAT how to add return type???
this.value+=operand;
return this;
}
subtract= (operand:number)=>{
this.value-=operand;
return this;
}
multiply= (operand:number)=>{
this.value*=operand;
return this;
}
divide= (operand:number)=>{
this.value/=operand;
return this;
}
}
我试过了:
add= (operand:number)=>number { ....
但它不起作用.
你可以写:
class BasicCalculator{ value:number; constructor(value:number=0){ this.value=value; } add = (operand:number):BasicCalculator =>{ this.value+=operand; return this; } subtract= (operand:number)=>{ this.value-=operand; return this; } multiply= (operand:number)=>{ this.value*=operand; return this; } divide= (operand:number)=>{ this.value/=operand; return this; } } let test = new BasicCalculator(); test.add(5);
但即使您没有为add
函数编写返回类型,TypeScript也可以在这种情况下推断出类型.您可以add
在操场上使用CTRL 将鼠标悬停在该功能上.