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

在作为激活函数参数的泛型构造函数返回类型中保留this

TypeScript 父子层级结构中保留父类类型的解决方案

你当前的问题核心是child方法的泛型定义没有正确绑定调用实例的类型,导致返回的子类型父类参数被推断为基类Parent而非当前子类的this类型。以下是具体的解决方法:

调整Parent类的child方法实现

修改child方法的泛型约束,让它直接关联当前实例的this类型,同时调整构造函数的类型签名,确保TypeScript能正确推断父类类型:

class Child<P extends Parent> {
  constructor(readonly parent: P) {}
}

class Parent {
  // 泛型T绑定到接收当前this作为父类的子类型
  child<T extends Child<this>>(ctor: new (parent: this) => T): T {
    return new ctor(this);
  }
}

验证效果

现在定义子类时,foo的类型会自动推断为MyChild<this>(即MyChild<MyParent>),完全符合预期:

class MyChild<P extends Parent> extends Child<P> { }

class MyParent extends Parent {
  foo = this.child(MyChild); // foo的类型为MyChild<MyParent>
}

// 支持多层继承场景
class MyGrandChild<P extends MyParent> extends Child<P> { }

class MyGrandParent extends MyParent {
  bar = this.child(MyGrandChild); // bar的类型为MyGrandChild<MyGrandParent>
}

原理说明

原代码中构造函数参数new <P extends Parent> (parent: P) => T是一个独立的泛型构造函数,TypeScript无法自动将调用时的this类型绑定到这个泛型参数上。修改后,我们让child方法的泛型直接关联当前实例的this类型,构造函数接收的父类参数就是this,从而让TypeScript正确推断出子类型的父类参数为当前实例的具体类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 00:45:14