To traverse through the union of element types in an array called arr
, you can utilize key remapping in mapped types by indexing into each member of the union to access the key and value properties:
const keyValueArrayToObject = <const T extends readonly { key: PropertyKey; value: any }[]>(
arr: T
) => {
return Object.fromEntries(arr.map(o => [o.key, o.value])) as
{ [U in T[number] as U['key']]: U['value'] };
};
A type assertion is needed here because TypeScript does not strongly type Object.fromEntries()
.
Now let's test this with an example:
const arrayOfKeyValue = [
{ key: 'a', value: 1 },
{ key: 'b', value: 'z' },
] as const;
const keyValueObject = keyValueArrayToObject(arrayOfKeyValue);
/* const keyValueObject: {
a: 1;
b: "z";
} */
This output looks good, but there are some recommendations. Firstly, use a const
assertion or similar on your array literal to ensure specific literal types for the keys and values. This will help TypeScript infer the correct types for your needs. If it's too specific, consider widening it manually or controlling the array literal types more precisely.
Playground link for code snippet