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

在TypeScript中能否基于数组元素生成对应的自定义类型?

可以实现,只需要按如下步骤操作即可:

  • 首先给数组添加as const断言,避免TS将数组类型放宽为string[],保留数组元素的字面量类型:
const keys = ['firstname', 'lastname'] as const

此时typeof keys会被推导为readonly ["firstname", "lastname"]类型。

  • 接着通过索引访问拿到数组元素的联合类型,再用映射类型或者Record工具类型定义NewType即可:
// 拿到数组元素的联合类型:"firstname" | "lastname"
type Keys = typeof keys[number]

// 方式1:用Record工具类型
type NewType = Record<Keys, any>

// 方式2:手写映射类型,效果和上面完全一致
type NewType = {
  [K in Keys]: any
}

注意:如果省略as const,TS会默认把keys推导为string[]类型,最终得到的NewType会变成允许任意字符串作为键的索引签名类型,不符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 19:39:02