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

TypeScript:如何更简洁地指定泛型类属性的方法返回类型

解决方案

最简洁方案:让TypeScript自动推断类型

直接去掉属性的显式类型声明,TypeScript会根据构造函数中的赋值自动推断property的类型,和你最初的属性初始化器写法效果完全一致:

export class BaseClass<T> {
  property;

  constructor(){
    this.property = this.buildProperty();
  }

  buildProperty(){
    return someBuilder<T>();
  }
}

显式声明类型的替代方案

如果需要明确对外暴露属性类型或满足代码规范,可选择以下两种方式避免重复书写BaseClass<T>:

方式1:利用类原型获取方法类型

通过BaseClass.prototype.buildProperty直接获取方法的类型,无需重复指定泛型参数:

export class BaseClass<T> {
  property: ReturnType<typeof BaseClass.prototype.buildProperty>;

  constructor(){
    this.property = this.buildProperty();
  }

  buildProperty(){
    return someBuilder<T>();
  }
}

方式2:用条件类型提取方法返回值

先定义通用类型工具,从实例类型中提取指定方法的返回值:

type MethodReturnType<Instance, MethodName extends keyof Instance> = 
  Instance[MethodName] extends (...args: any[]) => infer R ? R : never;

再在类中基于this类型使用该工具:

export class BaseClass<T> {
  property: MethodReturnType<this, 'buildProperty'>;

  constructor(){
    this.property = this.buildProperty();
  }

  buildProperty(){
    return someBuilder<T>();
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 01:50:32