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

继承类并覆写方法时,如何实现返回类型自动推断?

实现子类覆写方法后返回类型自动推断的方案

在TypeScript中,可以通过结合this类型和ReturnType工具类型,或者泛型类的方式,实现子类覆写父类方法后,相关调用方法的返回类型自动推断。以下是两种可行写法:

方案1:利用this类型与ReturnType工具类型

直接在父类的utilize方法中,通过ReturnType<this['example']>动态获取当前实例example方法的返回类型,子类覆写example后,类型会自动更新:

class Root {
  example(): string {
    return 'string';
  }

  utilize(): ReturnType<this['example']> {
    return this.example();
  }
}

class Child extends Root {
  example(): boolean {
    return true;
  }
}

// 测试:result的类型会自动推断为boolean
const child = new Child();
const result = child.utilize();

方案2:泛型类显式指定返回类型

将父类定义为泛型类,把example方法的返回类型作为泛型参数,子类继承时传入对应类型,同样能实现自动推断:

class Root<T = string> {
  example(): T {
    return 'string' as unknown as T;
  }

  utilize(): T {
    return this.example();
  }
}

class Child extends Root<boolean> {
  example(): boolean {
    return true;
  }
}

// 测试:result的类型为boolean
const child = new Child();
const result = child.utilize();

说明

以上两种方案都依赖TypeScript的类型系统,纯JavaScript由于是动态类型,不存在编译阶段的类型推断需求。第一种方案更简洁,无需显式声明泛型参数,TypeScript会基于this的实际类型自动推导example的返回类型;第二种方案则通过泛型参数明确约束类型,适合需要提前定义类型边界的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 10:15:27