【问题标题】:how do I assign the typing of a super to the child constructor如何将超级的类型分配给子构造函数
【发布时间】:2021-11-12 03:15:08
【问题描述】:

我正在寻找一种将父构造函数参数的类型传递给子构造函数的方法,例如

class B extends A {    
    constructor (input) {
        super(input);
    }
}

我试过了

class B extends A {    
    constructor (input : ConstructorParameters<typeof super>) {
        super(input);
    }
}

但是我从 eslint 'super' is not defined. 得到一个错误

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

    我认为您必须将 ConstructorParameters&lt;typeof A&gt;[0] 作为构造函数参数类型传递。

    class A {
      title: string;
      constructor(title: string) {
        this.title = title;
      }
    }
    
    class B extends A {
      constructor(title: ConstructorParameters<typeof A>[0]) {
        super(title);
      }
    }
    

    您可以尝试在评论中建议的其他解决方案:

      constructor(title: ConstructorParameters<typeof A>) {
        super(...title);
      }
    

    【讨论】:

    • 您也可以使用扩展运算符,这是更通用的解决方案。 Example
    • 传播参数可能对用户更友好constructor(...input: ConstructorParameters&lt;typeof A&gt;)。我们可以用new B(1) 代替new B([1])
    【解决方案2】:

    如果您不更改扩展类中的构造函数签名,那么就开发人员体验而言,这是 TypeScript 真正大放异彩的地方:您甚至不需要将构造函数包含在您的扩展课程,因为 TS 为您完成!

    TS Playground

    class A {
      input: string;
      constructor(input: string) {
        this.input = input;
      }
    }
    
    class B extends A {}
    
    new B(); /* Error
    ^^^^^^^
    Expected 1 arguments, but got 0.(2554) */
    
    new B('myInput'); // ok
    
    

    【讨论】:

      猜你喜欢
      • 2022-01-18
      • 1970-01-01
      • 2014-11-06
      • 1970-01-01
      • 2015-04-26
      • 2019-03-18
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多