K
K
kikosko2018-09-12 17:28:39
JavaScript
kikosko, 2018-09-12 17:28:39

Do you need to declare data types in a class, after an interface?

The Calculator class is implemented from ICalculator, where all the methods and their types are described, is it worth doing it again for class method parameters? If I remove it, then any type can be passed to the method. Please tell me how to write correctly, just started learning TypeScript

interface ICalculator {
    add(num: number): number;
    subtract(num: number): number;
    multiply(num: number): number;
    divide(num: number): number;
    print(): void;
}

class Calculator implements ICalculator {
    protected _res: number = 0;

    add(num:number) {
        return this._res = num + this._res;
    }

    subtract(num:number) {
        return this._res = this._res - num;
    }

    multiply(num:number) {
        return this._res = num * this._res;
    }

    divide(num:number) {
        return this._res = this._res / num ;
    }

    print():void {
        console.log(`Currently value: ${this._res}`);
    }
}
let myCalc = new Calculator();

myCalc.add(260);myCalc.subtract(12);
myCalc.multiply(12);myCalc.divide(2);
myCalc.print();

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question