通过泛型在 TypeScript 中元组到对象

Jac*_*her 3 generics tuples typescript

我正在尝试将 TypeScript 中的元组联合转换为对象,而不会丢失任何类型。

以下是它如何工作的示例:

type Tuples = ["foo", string] | ["bar", boolean] | ["baz", null];

/*
ideally the type would be:
{
  foo: string;
  bar: boolean;
  baz: null;
}
*/
type AsObject = DoSomething<Tuples>;
Run Code Online (Sandbox Code Playgroud)

上述问题的一个简单解决方案是:

type TupleToObject<T extends [string, any]> = { [key in T[0]]: T[1] };

/*
type is:
{
    foo: string | boolean | null;
    bar: string | boolean | null;
    baz: string | boolean | null;
}
*/
type TypesLost = TupleToObject<Tuples>;
Run Code Online (Sandbox Code Playgroud)

然而,我们丢失了一些类型信息,因为所有值都被拉到一个联合类型中。

我正在寻找一种使用泛型的解决方案,它不会丢失这种类型信息,并且希望对在 TypeScript 中映射泛型元组有更深入的了解。

Tit*_*mir 9

您可以通过使用 来获得所需的效果Extract。基本思想是我们将从T对应于 common 的联合中提取适当的类型key

type Tuples = ["foo", string] | ["bar", boolean] | ["baz", null];
type TupleToObject<T extends [string, any]> = { [key in T[0]]: Extract<T, [key, any]>[1] };

/*
type is:
{
    foo: string;
    bar: boolean;
    baz: null;
}
*/
type TypesLost = TupleToObject<Tuples>;
Run Code Online (Sandbox Code Playgroud)