typescript - 如何从对象数据集中的值创建字符串文字类型?
问题描述
我有一个从远程源获取的数据构建的大数据集,它看起来像这样:
[
{ id: 14, name: 'foo' },
{ id: 2, name: 'bar' },
{ id: 93, name: 'baz' },
...
]
我想创建这种类型:
type Name = 'foo'|'bar'|'baz'|...;
(然后从对象)
我认为值得注意的是该对象是从 json 文件导入的:
import data from './data.json'
我试过了
type Name = typeof data[number]['name']
但后来 Typescript 认为类型只是string
解决方案
我不知道您是否能够这样做,因为数据是从.json
文件加载的,但如果data
是常规变量,那么您可以使用它as const
来实现您正在寻找的东西
const x = [
{ id: 14, name: 'foo' },
{ id: 2, name: 'bar' },
{ id: 93, name: 'baz' },
] as const // <--- use as const here
type Name = typeof x[number]["name"] // Name is 'foo' | 'bar' | 'baz'
推荐阅读
- entity-framework - 如何在 DbContext 和 IdentityDbContext 之间创建桥接表?
- firebase - 如何使用颤振从 FireStore 获取所有用户?
- node.js - 如果直接从查询返回文档,则不会调用猫鼬模式转换
- java - Javers - 比较值为空的值对象和具有空列表的对象
- python - 检查 jupyter 笔记本是否运行时没有来自 cli 的错误
- multithreading - 将 RateLimiter 与线程一起使用
- python-2.7 - 使用 PyInstaller 将 kivy 应用程序转换为 .exe - CPU 使用率增加 0% 到 30%
- unit-testing - 如何将我的主 crate 导入到我的测试文件中?Rust 文档示例不起作用
- mysql - SQL SELECT 来自多个表的列的平均值
- python - 使用“计划”在 Python 中的确定时间仅运行一次计划任务