在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
相关产品推荐
相关产品推荐

