根据上面的数组,动态推导出 id的类型 type Id: 0 | 1 | 2, 应该怎么实现。望各位不吝赐教
已解决
悬赏分:40
- 解决时间 2021-11-27 21:39
点赞 0反对 0举报 0
收藏 0
分享 0
回答3
最佳
-
type TupleMapId<T extends {id:any}[]> = T[keyof T & number]['id'] type ActionId = TupleMapId<[{ id: 1, name: 'user1' }, { id: 2, name: 'user2' }, { id: 3, name: 'user3' }]>
只能做到这种程度,局限性挺大的
支持 0 反对 0 举报2021-11-27 03:24
-
const action = [ { id: 0, type: '编辑' }, { id: 1, type: '删除' }, { id: 2, type: '禁用' } ] as const type ActionId = typeof action[number]['id']
一个群友提了个方案使用 as const , 我觉得还可以。主要是之前压根不知道这个api。。
支持 0 反对 0 举报2021-11-27 04:24
-
// 类型推导是根据字面量基本类型进行的推导 interface Action { id: 1 | 2 | 3 name: string } // 如果不定义 Action类型 id 会被内置编译器 推导为number 这个没法改 const users: Action[] = [ { id: 1, name: 'user1' }, { id: 2, name: 'user2' }, { id: 3, name: 'user3' }, ] // 如果定义了 Action 直接去Action的属性type就行了 type UserId = Action['id']
支持 0 反对 0 举报2021-11-27 05:34