Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add return type information in a fat arrow method

Tags:

typescript

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.

like image 784
centeeth Avatar asked Jan 11 '16 07:01

centeeth


1 Answers

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.

like image 176
Martin Vseticka Avatar answered Sep 18 '22 20:09

Martin Vseticka