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

TypeScript接口如何定义返回实现类自身类型的方法,省略泛型参数

你想要的效果完全可以通过 TypeScript 的多态this类型实现,不需要给接口加泛型参数。

正确的接口定义如下:

interface Cloneable {
  clone(): this;
}

这里的this是 TypeScript 专门提供的多态类型,会自动指向当前实现该接口的类的实例类型,不需要手动传入泛型参数,完全匹配你想要的无泛型接口的效果。

实现类的写法如下:

class A implements Cloneable {
  clone(): this {
    // 若确定类不会被继承,也可以简写为 return new A() as this;
    return Object.create(this.constructor.prototype);
  }
  public sayA(){
    console.log("AAAA");
  }
}

class B implements Cloneable {
  clone(): this {
    return new B() as this;
  }
  public sayB(){
    console.log('BBB');
  }
}

调用效果和你原来的泛型写法完全一致,类型校验正常:

new A().clone().sayA(); // 类型正常,可正常调用sayA方法
new B().clone().sayB(); // 类型正常,可正常调用sayB方法

注意事项

  • 如果你的类后续可能会被子类继承,推荐使用Object.create(this.constructor.prototype)的方式创建克隆实例,能够保证子类继承后clone返回的类型和子类实例类型匹配。
  • 如果确定类不会被继承,直接使用new 类名() as this的写法更简洁直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 09:45:03