Some time ago, I shared my query on Inferring the shape of the result from Object.fromEntries() in TypeScript. The response I received seemed to work well for me until a couple of days back.
declare global {
interface ObjectConstructor {
fromEntries<
A extends ReadonlyArray<readonly [PropertyKey, any]>
>(array: A): { [K in A[number][0]]: Extract<A[number], readonly [K, any]>[1] }
}
}
This approach functions smoothly when A[number][0]
is mapped to precisely one type in each element. However, it encounters an issue if you specify that the first element of each tuple is a union type.
const x = Object.fromEntries(
[['a', 1], ['b', 2], ['c', 'foo']] as (['a' | 'b', number] | ['c', string])[]
);
// typeof x = { a: never, b: never; c: string; }
The problem arises because K
will always be either 'a'
or 'b'
, and given that 'a' | 'b'
does not extend 'a'
, it results in failure. I am aware of how to split a tuple of unions into unions of tuples, but only if the type of the second element remains consistent across all tuples, which may not be the case here.
Is there a way to adjust the definition of Object.fromEntries()
to accommodate keys with union types?