Skip to content

Instantly share code, notes, and snippets.

@okayurisotto
Created May 29, 2023 19:50
Show Gist options
  • Save okayurisotto/62357b372bcf980f60484c27c46fdc50 to your computer and use it in GitHub Desktop.
Save okayurisotto/62357b372bcf980f60484c27c46fdc50 to your computer and use it in GitHub Desktop.
export {};
type Entries = readonly Entry[];
type Entry = readonly [PropertyKey, unknown];
type EntryUnionToRecordUnion<T extends Entry> = T extends unknown
? Record<T[0], T[1]>
: never;
// https://stackoverflow.com/questions/50374908/#50375286
type UnionToIntersection<U> = (
U extends unknown ? (k: U) => void : never
) extends (k: infer I) => void
? I
: never;
declare class Object {
public static fromEntries<T extends Entries>(
entries: readonly [...T]
): UnionToIntersection<EntryUnionToRecordUnion<T[number]>>;
}
const entries = [
["key1", "value1"],
["key2", "value2"],
] as const satisfies Entries;
const object = Object.fromEntries(entries);
object.key1; // "value1"
object.key2; // "value2"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment