【问题标题】:Typescript - keyof values of array打字稿 - 数组的键值
【发布时间】:2020-06-04 05:11:13
【问题描述】:

我有一个清单

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

现在我想动态创建一个联合类型,描述如下:

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

有没有办法做到这一点?

我试图在这里调整这个想法:Keyof nested child objects 但我想不通

【问题讨论】:

    标签: typescript dynamic types union


    【解决方案1】:

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

    您必须改变分配list 的方式,至少在某种程度上是这样。最简单的做法(可能会也可能不会满足您的需求)是使用const assertion,它要求编译器推断出可能的最窄类型:

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

    现在list 被推断为类型:

    /* 
    const list: readonly [
        { readonly name: "parentTitle";}, 
        { readonly name: "anotherTitle";}, 
        { readonly name: "whatever";}
    ]
    */
    

    它是只读对象的只读元组,具有特定顺序的特定name 属性。由此我们可以使用lookup types 来定义Title

    type Title = typeof list[number]["name"];
    // type Title = "parentTitle" | "anotherTitle" | "whatever"
    

    好的,希望对您有所帮助;祝你好运!

    Playground link to code

    【讨论】:

    • 谢谢!很好的答案!但我想我还有另一个案例。我从 .json 文件中导入列表,而不是直接在打字稿中。但是我无法按照您的建议使用as const 定义json 文件的列表。有没有办法使用 json 文件中的列表来做到这一点?从'./list.json'导入列表; type Title = typeof list[number]['name'];
    • 如果需要导入 JSON,请将问题代码编辑为minimal reproducible example;恐怕导入 JSON 的选项是有限的。有一个request可以导入json文件as const,但是还没有实现。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-08-12
      • 1970-01-01
      • 2019-07-24
      • 2020-05-02
      • 2020-12-04
      • 2020-05-16
      • 1970-01-01
      • 2019-12-07
      • 2016-05-28
      相关资源
      最近更新 更多