通过泛型将元组转换为TypeScript中的对象

通过泛型将元组转换为TypeScript中的对象,typescript,generics,tuples,Typescript,Generics,Tuples,我试图将TypeScript中的元组联合转换为对象,而不丢失任何类型 下面是一个如何工作的示例: type Tuples = ["foo", string] | ["bar", boolean] | ["baz", null]; /* ideally the type would be: { foo: string; bar: boolean; baz: null; } */ type AsObject = DoSomething<Tuples>; type Tupl

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

下面是一个如何工作的示例:

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

/*
ideally the type would be:
{
  foo: string;
  bar: boolean;
  baz: null;
}
*/
type AsObject = DoSomething<Tuples>;
type Tuples=[“foo”,string]|[“bar”,boolean]|[“baz”,null];
/*
理想情况下,类型应为:
{
foo:string;
条形图:布尔型;
baz:null;
}
*/
aObject类型=剂量测定法;
解决上述问题的简单方法是:

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>;
type TupleToObject={[key in T[0]]:T[1]};
/*
类型为:
{
foo:string | boolean | null;
条形图:字符串|布尔值| null;
baz:string | boolean | null;
}
*/
类型TypesLost=TupleToObject;
但是,由于所有值都集中在一个联合类型中,因此我们会丢失一些类型信息


我正在寻找一种使用泛型的解决方案,它不会丢失这种类型信息,如果您能更深入地了解在TypeScript中映射泛型元组,我将不胜感激。

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

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>;
type Tuples=[“foo”,string]|[“bar”,boolean]|[“baz”,null];
键入TupleToObject={[T[0]]中的键:Extract[1]};
/*
类型为:
{
foo:string;
条形图:布尔型;
baz:null;
}
*/
类型TypesLost=TupleToObject;

完美!谢谢你治好了我的头痛<代码>摘录
正是我想说的。