Inheritance 使用…args调用super()
如何使用相同的参数调用超级构造函数,如当前构造函数调用Inheritance 使用…args调用super(),inheritance,typescript,Inheritance,Typescript,如何使用相同的参数调用超级构造函数,如当前构造函数调用 class B { constructor(...args) { } } class C extends B { constructor(...args) { // Here is an compile error. super(...args); } } 不幸的是,TypeScript编译器本机不接受这一点。您可以稍微重构它,以便基类构造函数接受一个数组或一个参数数组:
class B {
constructor(...args) {
}
}
class C extends B {
constructor(...args) {
// Here is an compile error.
super(...args);
}
}
不幸的是,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);
}
}