TypeScript如何将父类构造函数的参数类型应用到子类构造函数
super是JavaScript内置的语法关键字,不属于可被typeof运算符读取类型的有效值,因此typeof super属于非法写法,会触发ESLint的'super' is not defined报错。
你只需要将typeof super替换为父类本身的类型引用typeof A即可实现需求,可按场景选择以下写法:
- 父类构造函数仅接收单个参数的场景
class B extends A { constructor (input: ConstructorParameters<typeof A>[0]) { super(input); } }
- 通用兼容场景(适配父类构造函数任意参数数量,父类构造参数修改后子类类型会自动同步,无需手动调整)
class B extends A { constructor (...args: ConstructorParameters<typeof A>) { super(...args); } }
如果子类需要额外新增自定义参数,可基于上述逻辑扩展:
// 示例:子类构造在父类参数基础上额外增加一个字符串类型的extra参数 class B extends A { constructor (...args: [...ConstructorParameters<typeof A>, extra: string]) { super(...args.slice(0, -1) as ConstructorParameters<typeof A>); // 后续自定义逻辑处理新增的extra参数 } }
内容的提问来源于stack exchange,提问作者A. L
相关产品推荐
相关产品推荐

