You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript 如何为子类构造函数的指定入参设置更严格的类型

解决方案

你可以通过类型推断提取父类构造参数排除首参数的剩余类型,组合自定义的首参数类型实现需求,完整实现代码如下:

// 通用工具类型:提取数组/元组排除第一个元素后的剩余类型
type Tail<T extends any[]> = T extends [any, ...infer Rest] ? Rest : never;

class Animal {}
// Dog是Animal的子类,有独有方法bark
class Dog extends Animal {
  bark() {
    console.log('汪汪叫');
  }
}

class Parent {
  constructor(a: Animal, b: number, c: number) {}
}

class Child extends Parent {
  // 首参数替换为Dog类型,剩余参数自动同步父类构造参数的剩余部分
  constructor(a: Dog, ...args: Tail<ConstructorParameters<typeof Parent>>) {
    super(a, ...args);
    a.bark(); // 类型正常,可直接调用Dog独有的方法
  }
}

// 效果验证
new Child(new Animal(), 0, 0); // 类型报错,不符合预期的首参数类型
new Child(new Dog(), 0, 0); // 类型正常,可正常运行

方案优势

后续如果父类构造函数新增任意参数,子类不需要做任何修改,会自动继承后续所有参数的类型约束,调用子类构造函数时也会自动要求传入对应类型的后续参数,完全满足你不需要手动同步父类参数变更的需求。

内容的提问来源于stack exchange,提问作者Shnick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 08:06:03