如何从数组对象中获取类型

时间:2021-06-22 03:40:21

标签: typescript types

type Item = {
  id: string;
  value: string;
};

const items: Readonly<Item>[] = [
  { id: 'id1', value: 'TODO1' },
  { id: 'id2', value: 'TODO2' },
  { id: 'id3', value: 'TODO3' },
];

我想获得类型 'TODO1' | '待办事项2' | 'TODO3';

const items = [...] as const;

type Type = typeof items[number]['value'];

我可以通过 const 断言获取类型。但是在这种情况下,我丢失了我的物品类型..

1 个答案:

答案 0 :(得分:1)

您可以先定义数组 as const,然后再将其分配给 items

const itemsInitial = [
  { id: 'id1', value: 'TODO1' } as const,
  { id: 'id2', value: 'TODO2' } as const,
  { id: 'id3', value: 'TODO3' } as const,
];
type Type = typeof itemsInitial[number]['value'];
const items: Readonly<Item>[] = itemsInitial;

但是,鉴于问题中的代码,您可能根本不需要 Item 类型 - 我认为还不需要它,或者不需要 Readonly<Item>[] 类型。