【问题标题】:Create object type from union of keys从键的联合创建对象类型
【发布时间】:2019-04-13 19:38:01
【问题描述】:

我知道keyof 运算符以及如何创建由该对象的键组成的联合类型,如下所示:

interface Foo {
  a: string;
  b: string;
}

type Goo = keyof Foo; // "a" | "b"

我想做完全相反的事情,并从键的联合中创建一个新的对象类型。

const MakeTuple = <T extends string[]>(...args: T) => args;
const Types = MakeTuple("A", "B", "C");
type TypeVariant = typeof Types[number];

type VariantObject = {
  // This gives error consider using a mapped object but I'm not sure how to do that
  [type: TypeVariant]: [boolean, boolean, boolean, string[]];
}

所以我想要的是获取键的联合并生成一个类型,其中包含[boolean, boolean, boolean, string[]] 类型的每个键的值。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以只使用预定义的Record 映射类型

    const MakeTuple = <T extends string[]>(...args: T) => args;
    const Types = MakeTuple("A", "B", "C");
    type TypeVariant = typeof Types[number];
    
    type VariantObject = Record< TypeVariant, [boolean, boolean, boolean, string[]] >
    

    【讨论】:

      猜你喜欢
      • 2020-02-08
      • 2018-09-06
      • 2022-01-03
      • 2021-11-26
      • 2020-05-21
      • 2019-10-20
      • 2018-11-13
      • 1970-01-01
      • 2020-03-04
      相关资源
      最近更新 更多