通过键并集创建对象类型

时间:2019-04-13 09:07:42

标签: typescript

我了解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[]]的每个键的值。

1 个答案:

答案 0 :(得分:2)

您可以只使用预定义的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[]] >