Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript-数组值的键_Typescript_Dynamic_Types_Union - Fatal编程技术网

Typescript-数组值的键

Typescript-数组值的键,typescript,dynamic,types,union,Typescript,Dynamic,Types,Union,我有一张单子 导出常量列表=[ { 姓名:'parentTitle', }, { 姓名:'另一个头衔', }, { 名字:“随便什么”, }, ]; 现在,我想动态创建一个联合类型,它描述了以下内容: type Title='parentTitle'|'anotherTitle'|'whatever'; 有办法做到这一点吗 我试着在这里适应这个想法: 但是我想不出来你可以为它创建一个接口,并从中创建一个数组类型 interface Title { name: 'parentTitle

我有一张单子

导出常量列表=[
{
姓名:'parentTitle',
},
{
姓名:'另一个头衔',
},
{
名字:“随便什么”,
},
];
现在,我想动态创建一个联合类型,它描述了以下内容:

type Title='parentTitle'|'anotherTitle'|'whatever';
有办法做到这一点吗

我试着在这里适应这个想法:
但是我想不出来

你可以为它创建一个接口,并从中创建一个数组类型

interface Title {
    name: 'parentTitle' | 'anotherTitle' | 'whatever';
}

let list: Title[] = [
  {
    name: 'parentTitle',
  },
  {
    name: 'anotherTitle',
  },
  {
    name: 'whatever',
  },
];

在您的示例中,
列表
的类型被编译器推断为
数组
,因此,在您尝试定义
标题
时,编译器已经完全忘记了
名称
属性的具体内容

您必须至少在一定程度上更改分配
列表的方式。最简单的方法(可能满足您的需要,也可能不满足您的需要)是使用,它要求编译器推断出可能的最窄类型:

export const list = [
    { name: 'parentTitle', },
    { name: 'anotherTitle', },
    { name: 'whatever', },
] as const;
现在,
列表
被推断为以下类型:

/* 
const list: readonly [
    { readonly name: "parentTitle";}, 
    { readonly name: "anotherTitle";}, 
    { readonly name: "whatever";}
]
*/
它是只读对象的只读元组,具有特定顺序的特定
name
属性。从中我们可以定义
标题

type Title = typeof list[number]["name"];
// type Title = "parentTitle" | "anotherTitle" | "whatever"
好吧,希望这会有帮助;祝你好运


谢谢!回答得好!但我想我还有一个案子。我从.json文件导入列表,而不是直接在typescript中导入。但是我不能像您建议的那样将json文件的列表定义为const
。有没有办法通过json文件中的列表来实现这一点?从“/list.json”导入列表;类型标题=列表的类型[编号]['name'];如果需要导入JSON,请将问题代码编辑为a;恐怕导入JSON的选项是有限的。有一种方法可以将json文件
导入为const
,但尚未实现。