我有一组物体,
const myObj = [
{ key: 'orange', value: 1 },
{ key: 'apple', value: 1 }
]
现在,我想从myObj
数组中提取类型,'orange' | 'apple'
.我如何做到这一点?
我有一组物体,
const myObj = [
{ key: 'orange', value: 1 },
{ key: 'apple', value: 1 }
]
现在,我想从myObj
数组中提取类型,'orange' | 'apple'
.我如何做到这一点?
你必须做两件事.
使用const assertion尽可能缩小object
的类型.然后一般地提取密钥.
const myObj = [
{ key: 'orange', value: 1 },
{ key: 'apple', value: 1 }
] as const;
type keyType = typeof myObj[number]['key'];
常量断言对你myObj
以上做了几件事,其中之一是-防止类型的扩大.因此,不是将key
推断为string
,而是将其推断为orange | apple
.