I'm trying to create a type that takes two lists as an input:
Keys: ["foo", "bar", "baz"]
Values: [50, number, "abc"]
to, then, output the following object composed from their keys and values:
{
foo: 50,
bar: number,
baz: "abc"
}
type UnionToIntersection<T> = (T extends object ? (k: T) => void : never) extends (k: infer U) => void ? U : never;
type KeyValuePairsFromLists<
Keys extends Array<string | number>,
Values extends Array<any>
> = {
[index in keyof Keys]: index extends keyof Values
? [Keys[index], Values[index]]
: never;
};
type ObjectFromKeyValuePairs<
KV extends Array<[string | number, any]>,
T = {
[index in keyof KV]: KV[index] extends [string | number, any]
? Record<KV[index][0], KV[index][1]>
: never;
}
> = UnionToIntersection<T[keyof T]>;
type ObjectFromKeyValueArrays<
Keys extends Array<string | number>,
Values extends Array<any>
> = ObjectFromKeyValuePairs<KeyValuePairsFromLists<Keys, Values>>;
const myObj = {} as ObjectFromKeyValueArrays<
["foo", "bar"],
[5, "bar"]
>;
type foo = typeof myObj.foo // 5
type bar = typeof myObj.bar // string
The way I'm doing it now is by converting the arrays into key/value pairs, then mapping them to a union of objects with a single key, and converting that to an intersection to get the final object.
Is there some better way of achieving this? Am I doing this wrong?
ObjectFromKeyValuePairs<KeyValuePairsFromLists<Keys, Values>>
type ObjectFromKeyValueArrays<Keys extends string[], Values extends any[] & Pick<Keys,"length">>
gave me nice coupling between length of Key array and Value array which could eliminate some cases.