centeeth
centeeth

Reputation: 365

Add return type information in a fat arrow method

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.

Upvotes: 7

Views: 3996

Answers (1)

MartyIX
MartyIX

Reputation: 28646

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.

Upvotes: 10

Related Questions