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

如何让TypeScript自动推导继承方法的返回类型?

让TypeScript自动推断wrapperMethod的返回类型为子类childMethod的返回值

你的问题核心是抽象类的wrapperMethod返回类型固定为unknown,导致子类调用时无法自动识别实际返回类型。下面提供两种可行的解决方式:

方案一:使用泛型约束抽象类

给抽象类添加泛型参数,明确childMethod和wrapperMethod的返回类型关联:

export abstract class WrapperClass<T> {
  protected abstract childMethod(): T;

  wrapperMethod(): T {
    const result = this.childMethod();
    return result;
  }
}

子类继承时指定泛型参数为ChildResponse:

export class ChildClass extends WrapperClass<ChildResponse> {
  protected childMethod(): ChildResponse {
    const response = new ChildResponse();
    return response;
  }
}

此时调用代码中,response会被TypeScript自动推断为ChildResponse类型:

const childClass = new ChildClass();
const response = childClass.wrapperMethod(); // 类型为ChildResponse
console.log(response.id); // 无类型报错

方案二:利用ReturnType和this类型自动推断

如果不想显式声明泛型,可以通过ReturnType工具类型结合this上下文,让TypeScript自动推导返回类型:

export abstract class WrapperClass {
  protected abstract childMethod(): unknown;

  wrapperMethod(): ReturnType<this["childMethod"]> {
    // 类型断言用于让TypeScript确认返回值匹配推导类型
    return this.childMethod() as ReturnType<this["childMethod"]>;
  }
}

子类无需额外修改,保持原有写法即可:

export class ChildClass extends WrapperClass {
  protected childMethod(): ChildResponse {
    const response = new ChildResponse();
    return response;
  }
}

这种方式下,wrapperMethod的返回类型会自动跟随子类childMethod的返回类型变化,调用时同样能正确推断response为ChildResponse。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 02:15:37