typescript - 如何从数组对象中获取类型
问题描述
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 断言得到一个类型。但是这种情况下,我丢失了我的项目类型..
解决方案
您可以最初定义数组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 类型 -鉴于问题中的代码,我认为还不需要它,或者不需要该类型。
推荐阅读
- kubernetes - Kubernetes pod 规范 - 是否可以指定 NodeAffinity 来选择请求最多的节点
- ios - 无法关闭菜单选择 IOS - React Native
- c# - EventHubTrigger C# 与 EventData 对象
- r - “边际”如何计算线性模型中的边际效应?
- python - 将第一行和标题与熊猫组合
- xamarin - Xamarin 总是响亮的推送通知
- python - 在 Windows 中从 .ui 文件转换为 .py 文件时的格式问题
- python - 多处理 Python 3
- excel - 使用excel vba在逗号分隔列中查找字符串
- r - 在服务器上托管的 R 闪亮工具上上传大文件