Skip to content

Instantly share code, notes, and snippets.

@alexilyaev
Last active May 31, 2023 08:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexilyaev/3fe3e6e6065b9f19450ac52a11209f52 to your computer and use it in GitHub Desktop.
Save alexilyaev/3fe3e6e6065b9f19450ac52a11209f52 to your computer and use it in GitHub Desktop.
Object.keys() on a typed Object loses it's keys type

Object.keys() on a typed Object loses it's keys type

Playground with examples

How is it different than ts-extra > objectKeys?

Source file

  • Preserves the keys type of a typed object instead of getting a union of the actual keys values (see playground)

TL;DR

/**
 * A strongly-typed version of `Object.keys()`
 *
 * Details:
 * https://gist.github.com/alexilyaev/3fe3e6e6065b9f19450ac52a11209f52
 */
export const objectKeysTyped = Object.keys as <Type extends object>(
  value: Type
) => Array<keyof typeof value>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment