Calculator类是从ICalculator实现的,其中描述了所有方法及其类型,是否值得对类方法参数再次执行此操作?如果删除,则可以将任何数据类型传递给该方法。请告诉我如何正确书写,我才刚开始学习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();