代码之家  ›  专栏  ›  技术社区  ›  zedryas

Typescript使用rest参数在子断点内生成新实例

  •  0
  • zedryas  · 技术社区  · 7 年前

    我正在尝试创建一个父类,子类可以为其生成同类型子类的新实例。

    如果我指定参数的数量,一切都正常:

    abstract class AClass {
    
      protected sameTypeWithSingle (
        x: any
      ): this {
        const self = this as this & {
          constructor: { new (x: any) }
        }
        return new self.constructor (x)
      }
    
      protected sameTypeWithDouble (
        a: any, b: any
      ): this {
        const self = this as this & {
          constructor: { new (a: any, b: any) }
        }
        return new self.constructor (a, b)
      }
    }
    

    但是,如果我尝试使用任意数量的参数(因此匹配任何子构造函数签名),它将不起作用(在comment中是typescript错误:

    abstract class AClass {
    
      protected sameTypeWith (
        ...args: any[]
      ): this {
        const self = this as this & {
          constructor: { new (...args: any[]) }
        }
        return new self.constructor (...args)
        // [ts] Cannot use 'new' with an expression whose type
        // lacks a call or construct signature.
      }
    }
    

    首先,我不明白为什么它会中断-它与两个参数,但不与任何? 此外,他们是实现我想要的一种方式?

    提前谢谢

    Seb公司

    1 回复  |  直到 7 年前
        1
  •  1
  •   jcalz    7 年前

    我同意这很奇怪。你看得出来 self.constructor 属于类型 Function & (new (...args: any[]) => any) ,应该是新的。但是编译器中发生了一些事情来防止这种情况,可能是 new (...args: any[]) 这会产生意想不到的副作用。如果我有时间的话,我可能会追查这件事,或者提交一份文件 issue

    编辑:正如@MattMcCutchen评论的,看起来这是 filed as a bug submitted a pull request to fix it


    作为一种解决方法,您可以通过以下更改实现您想要的:

    abstract class AClass {
      protected sameTypeWith(
        ...args: any[]
      ): this {
        const self = this as this & {
          constructor: { new(arg0?: any, ...args: any[]): any } // change here
        };
        return new self.constructor(...args); // works
      }
    }
    

    any 后跟类型为的rest参数 any[] 只相当于

    推荐文章