Last active
March 31, 2023 09:51
-
-
Save karol-majewski/b234a4aceb8884ccc1acf25a2e1ed16e to your computer and use it in GitHub Desktop.
Type inference for literal types with Object.fromEntries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Primitive = | |
| boolean | |
| number | |
| string | |
| bigint | |
| symbol | |
| null | |
| undefined; | |
type Narrowable = | |
| Primitive | |
| object | |
| {}; | |
type Entry<K extends PropertyKey, V> = [K, V]; | |
/** | |
* @author https://stackoverflow.com/users/2887218/jcalz | |
* @see https://stackoverflow.com/a/50375286/10325032 | |
*/ | |
type UnionToIntersection<Union> = | |
(Union extends any | |
? (argument: Union) => void | |
: never | |
) extends (argument: infer Intersection) => void | |
? Intersection | |
: never; | |
type FromEntries<T extends Entry<K, V>, K extends PropertyKey, V extends Narrowable> = | |
UnionToIntersection< | |
T extends [infer Key, infer Value] | |
? Key extends PropertyKey | |
? Record<Key, Value> | |
: never | |
: never | |
> | |
function fromEntries<T extends Entry<K, V>, K extends PropertyKey, V extends Narrowable>( | |
entries: Iterable<T>, | |
): FromEntries<T, K, V> { | |
return [...entries].reduce( | |
(accumulator, [key, value]) => | |
Object.assign(accumulator, { | |
[key.toString()]: value, | |
}), | |
{} as FromEntries<T, K, V>, | |
); | |
} | |
fromEntries([ | |
['foo', 1], | |
['bar', 2] | |
]); // #ExpectType { foo: 1, bar: 2} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use this definition to overload
Object.fromEntries
: