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

如何使用泛型向TBody传递任意类型替换user字段的any类型

解决方案

你可以将TBody定义为带泛型参数的类型,使用时传入对应类型即可替换user字段的原有类型:

改写泛型版TBody

// 泛型参数T可设置默认值,这里设置为unknown比any更安全
type TBody<T = unknown> = {
  success: boolean,
  user?: T
}

使用示例

传入TUserInfo作为泛型参数

// 此时user字段类型为 TUserInfo | undefined
const response: TBody<TUserInfo> = {
  success: true,
  user: {
    id: 123,
    fname: 'Jack',
    lname: 'Ma'
  }
}

其他场景使用

你可以任意传入其他类型作为泛型参数,适配不同的返回体结构:

// 传入string类型,user字段类型为 string | undefined
const stringRes: TBody<string> = {
  success: false,
  user: '参数错误'
}

补充说明

  • 你原定义的TUserInfo中id字段的num为笔误,TypeScript 中数字类型关键字为number
  • 如果需要限制泛型只能传入特定类型(比如只能是对象),可以给泛型加约束:type TBody<T extends object = unknown>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 14:06:03