用... args调用super()

时间:2014-06-06 00:54:33

标签: inheritance typescript

如何调用具有相同参数的超级构造函数,如当前构造函数调用?

class B {
    constructor(...args) {
    }
}

class C extends B {
    constructor(...args) {
        // Here is an compile error.
        super(...args);
    }
}

1 个答案:

答案 0 :(得分:1)

不幸的是,TypeScript编译器本身不接受这种情况。你可以稍微重构它,以便基类构造函数接受一个数组一个参数数组:

class B {
    constructor(...args: string[]);
    constructor(argsArray: string[]);
    constructor(...args: any[]) {
        if(args && args.length === 1 && args[0] instanceof Array) {
            // Use args[0] as string[]
        } else {
            // Use args as string[]
        }
    }
}

class C extends B {
    constructor(...args: string[]) {
        // OK
        super(args);
    }
}