【问题标题】:How to Group all property option in Array of Objects如何对对象数组中的所有属性选项进行分组
【发布时间】:2022-01-11 04:12:42
【问题描述】:
我想在某些属性中获取数组的类型
并通过打字稿输入自动编译
const arr = [{test:'option 1'},{test: 'option 2'}]
type test = arr[number]['test']
let t:test = '' // will equal 'option 1' or 'option 2'
【问题讨论】:
标签:
typescript
types
typescript-typings
【解决方案1】:
您需要将 arr 转换为 const,以便 typescript 可以正确推断其类型,例如
const arr = [{test:'option 1'},{test: 'option 2'}] as const; // <-- cast to const here
type test = typeof arr[number]['test'];
let t:test = ''; // will equal 'option 1' or 'option 2'