I searched in all possible ways but I can't figure out how to combine return type annotation and fat arrow syntax.
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;
}
}
I tried:
add= (operand:number)=>number { ....
but it doesn't work.
You can write:
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);
But even if you don't write the return type for add
function, TypeScript can infer the type in this situation. You can hover your mouse over the add
function with CTRL in the playground.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With