首页 > 解决方案 > 如何从对象数据集中的值创建字符串文字类型?

问题描述

我有一个从远程源获取的数据构建的大数据集,它看起来像这样:

[
  { 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

标签: typescript

解决方案


我不知道您是否能够这样做,因为数据是从.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'

推荐阅读