【问题标题】:Typescript error when passing arguments to super class. `A spread argument must either have a tuple type or be passed to a rest parameter (TS2556).`将参数传递给超类时出现打字稿错误。 `扩展参数必须具有元组类型或传递给休息参数 (TS2556)。`
【发布时间】:2021-11-09 23:31:16
【问题描述】:

以下给出错误 TS2556,我该如何解决?

class Test {
    constructor(x: number) {}
}

class Test2 extends Test {
    constructor(...args) {
        super(...args); // TS2556
    }
}

或者,如果您使用带有 tsc 的 jsdoc 进行类型检查:

class Test {
    /**
     * @param {number} x
     */
    constructor(x) {}
}

class Test2 extends Test {
    constructor(...args) {
        super(...args);
    }
}

【问题讨论】:

    标签: typescript super jsdoc spread


    【解决方案1】:

    使用ConstructorParameters<T>,如果你正在调用一个函数,你可以只使用Parameters<T>

    class Test {
        constructor(x: number) {}
    }
    
    class Test2 extends Test {
        constructor(...args: ConstructorParameters<typeof Test>) {
            super(...args);
        }
    }
    

    或者对于jsdoc:

    class Test {
        /**
         * @param {number} x
         */
        constructor(x) {}
    }
    
    class Test2 extends Test {
        /**
         * @param  {ConstructorParameters<typeof Test>} args
         */
        constructor(...args) {
            super(...args);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-16
      • 2014-11-14
      • 2020-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多