Last active
January 30, 2021 06:33
-
-
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
This file contains 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
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