Skip to content

Instantly share code, notes, and snippets.

@Shrugsy
Last active January 30, 2021 06:33
Show Gist options
  • Save Shrugsy/6d43fc36e8f6a7f42e859bc6b8f69f3a to your computer and use it in GitHub Desktop.
Save Shrugsy/6d43fc36e8f6a7f42e859bc6b8f69f3a to your computer and use it in GitHub Desktop.
Allows using `Object.entries` with Typescript while retaining key type information with. Example: https://tsplay.dev/aNnPdW. Note: see discussion here before using this, as keys are intentionally typed as only `string` by design: https://github.com/microsoft/TypeScript/pull/12253
export type Entries<T> = {
[K in keyof T]: [K, T[K]];
}[keyof T][];
/**
* Helper to use `Object.entries` while retaining key type information.
* Input object should be cast `as const` for maximum effectiveness.
*/
export function objEntries<T extends Record<string, unknown>>(obj: T): Entries<T> {
return Object.entries(obj) as Entries<T>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment