首页 > 解决方案 > 如何从数组对象中获取类型

问题描述

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 断言得到一个类型。但是这种情况下,我丢失了我的项目类型..

标签: typescripttypes

解决方案


您可以最初定义数组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;

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


推荐阅读