ts 如何生成数组对象指定 key 的类型?
数组对象的 key 的类型
有一个数组如下:
const list = [
{
key: '001',
value: 'xxx',
},
{
key: '002',
value: 'xxx'
},
{
key: '003',
value: 'xxx'
},
// ...
]
如何生成一个联合类型 Keys:
type Keys = '001' | '002' | '003' | ...
对象的 key 的类型
有一个对象如下:
const obj = {
'001': {
label: '001',
value: 'xxx',
},
'002': {
label: '002',
value: 'xxx'
},
'003': {
label: '002',
value: 'xxx'
},
// ...
}
如何生成一个联合类型 Keys:
type Keys = '001' | '002' | '003' | ...
根据 @kkopite 的回复,可以这样做:
const obj = {
'001': {
label: '001',
value: 'xxx',
},
'002': {
label: '002',
value: 'xxx'
},
'003': {
label: '002',
value: 'xxx'
},
// ...
} as const
type P = keyof typeof obj
如果给 obj 声明一个类型:
type Obj = {
[key: string]: {
label: string
value: string
}
}
const obj: Obj = {
'001': {
label: '001',
value: 'xxx',
},
'002': {
label: '002',
value: 'xxx'
},
'003': {
label: '002',
value: 'xxx'
},
// ...
} as const
type P = keyof typeof obj
推导将会失效:
请问如何解决呢?
回复
1个回答

test
2024-07-12
const list = [
{
key: '001',
value: 'xxx',
},
{
key: '002',
value: 'xxx'
},
{
key: '003',
value: 'xxx'
},
// ...
] as const
type Keys = typeof list[number]['key']
你已经指定了obj
的类型为Obj
,此时keyof typeof obj
就是等价于keyof Obj
了,这种情况可以通过定义一个函数加上泛型来解决:
type Obj = {
[key: string]: {
label: string
value: string
}
}
function d<T extends Obj>(obj: T) {
return obj
}
const obj = d({
'001': {
label: '001',
value: 'xxx',
},
'002': {
label: '002',
value: 'xxx'
},
'003': {
label: '002',
value: 'xxx'
},
'3': {
label: '11',
value: '112'
}
// ...
})
type P = keyof typeof obj
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容