You need to enable JavaScript to run this app. TypeScript能否通过对象字段名动态推导方法返回类型?
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript能否通过对象字段名动态推导方法返回类型?

解决TypeScript User类get方法自动推导返回类型的问题

完全可以实现这个需求,只需要调整get方法的泛型定义,让泛型与传入的字段名做类型绑定即可。

修改后的代码如下:

export interface UserModel {
  id: number
  name: string
  email: string
}

export class User {
  constructor(private _user: UserModel | null) {
  }

  // 泛型K绑定字段名,返回类型自动对应UserModel的该字段类型
  public get<K extends keyof UserModel>(name: K): UserModel[K] {
    if (this._user === null) {
        throw new Error("User is empty.");
    }

    // 无需类型断言,类型已自动匹配
    return this._user[name]
  }

  public isGuest(): boolean {
    return this._user === null;
  }
}

关键说明:

  • 把原来的泛型T替换为K extends keyof UserModel,K表示传入的字段名的类型,extends keyof UserModel确保只能传入UserModel中存在的字段,避免传错字段名。
  • 返回类型定义为UserModel[K],这是TypeScript的索引类型查询语法,表示取UserModel中K对应字段的类型。当你传入具体的字段名(比如'email')时,TypeScript会自动推导K为'email',进而返回类型就是UserModel['email']即string。

验证效果:

const user = new User({ id: 1, name: '张三', email: 'zhangsan@example.com' })

user.get('email') // 自动推导返回类型为string
user.get('id')    // 自动推导返回类型为number
user.get('name')  // 自动推导返回类型为string

这样就完全符合你的需求,不需要手动传入泛型,TypeScript会根据字段名自动识别返回类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:55:16