Typescript-数组的键值

问题描述 投票:0回答:2

我有一个清单

export const list = [
  {
    name: 'parentTitle',
  },
  {
    name: 'anotherTitle',
  },
  {
    name: 'whatever',
  },
];

现在,我想动态创建一个描述以下内容的联合类型:

type Title = 'parentTitle' | 'anotherTitle' | 'whatever';

有没有办法做到这一点?

我试图在这里调整主意:Keyof nested child objects但我无法弄清楚

typescript dynamic types union
2个回答
0
投票

您可以为其创建接口并从中创建数组类型。


0
投票

在您的示例中,list的类型被编译器推断为Array<{name: string}>,因此,当您尝试定义string literal types时,编译器已经完全忘记了name属性的特定Title。 。

© www.soinside.com 2019 - 2024. All rights reserved.