我是TypeScript
的新手,请告诉我如何优化这段代码中的数据类型,这是我一直以来number
不会写的。我了解到可以做到这一点,可以通过generics
告诉我如何正确简要地描述此代码
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;
add(num:number) {
return this._res = num + num;
}
subtract(num:number) {
return this._res = num - num;
}
multiply(num:number) {
return this._res = num * num;
}
divide(num:number) {
return this._res = num / num;
}
print():void {
console.log(`Currently value: ${this._res}`);
}
}
let calc1 = new Calculator();
calc1.add(1);calc1.add(1);
calc1.print();
答案 0 :(得分:3)
由于您已经写出了接口中每个函数的类型定义,因此在定义它们时可以跳过向其重新添加类型的过程。
这在类型上是相同的:
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;
add(num) {
return this._res = num + num;
}
subtract(num) {
return this._res = num - num;
}
multiply(num) {
return this._res = num * num;
}
divide(num) {
return this._res = num / num;
}
print() {
console.log(`Currently value: ${this._res}`);
}
}
您还可以定义函数的类型以进行更多重构:
type NumberOperation = (num: number) => number
interface ICalculator {
add: NumberOperation
subtract: NumberOperation
multiply: NumberOperation
divide: NumberOperation
print(): void;
}
编辑:
Titian Cernicova-Dragomir是正确的Class method parameter are never inferred, they will be implicitly typed to any
如果您不想在类内键入每个函数,则可以在声明类实例时使用该接口:
const calc: ICalculator = new Calculator()
calc.add('string') // type error