请教一个 ts 动态类型推导的实现?

QQ图片20191226164136.png

根据上面的数组,动态推导出 id的类型 type Id: 0 | 1 | 2, 应该怎么实现。望各位不吝赐教

阅读 8.2k
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'
        }]>
    

只能做到这种程度,局限性挺大的

const action = [
  {
    id: 0,
    type: '编辑'
  },
  {
    id: 1,
    type: '删除'
  },
  {
    id: 2,
    type: '禁用'
  }
] as const

type ActionId = typeof action[number]['id']

一个群友提了个方案使用 as const , 我觉得还可以。主要是之前压根不知道这个api。。

// 类型推导是根据字面量基本类型进行的推导
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']
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题