【问题标题】:Type 'Function' has no construct signatures.ts类型 \'Function\' 没有构造 signatures.ts
【发布时间】: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


【解决方案1】:

我能够通过从 return 语句中删除 new 来解决这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-13
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    相关资源
    最近更新 更多