【发布时间】:2023-01-30 03:36:20
【问题描述】:
我正在尝试将我的 JS 重写为 TS。我有一个名为 Point2D 的类,用于操作二维点。我收到一个错误 Type 'Function' has no construct signatures.ts(2351)。转移到 TS 时我做错了什么?
class Point2D {
x: number;
y: number;
public constructor(x: number = 0, y: number = 0) {
this.x = x;
this.y = y;
}
/**
* Translate this point by that point
*
* @param {Point2D} that
*/
public add(that: Point2D) {
return new this.constructor(this.x + that.x, this.y + that.y); // ERROR
}
public subtract(that: Point2D) {
return new this.constructor(this.x - that.x, this.y - that.y); // ERROR
}
/**
*
* @param {number} scalar
*/
public multiply(scalar:number) {
return new this.constructor(this.x * scalar, this.y * scalar); // ERROR
}
}
export default Point2D;
【问题讨论】:
-
this.constructor 是一个函数,你用一个函数调用
new。 -
this.constructor不是类型安全的,因为子类可能具有接受完全不同参数的构造函数,如 in this playground link 所示。为什么不直接使用Point2D而不是this.constructor,如图in this playground link?然后它是类型安全的,编译器对此很满意。这是否完全解决了您的问题?如果是这样,我会写一个完整解释的答案;如果没有,我错过了什么?
标签: typescript