DEV Community

Etienne Burdet
Etienne Burdet

Posted on

The best TS utility ever. EVER!

So enums are dead, right? Long live the as const:

const ODirection = {
  Up: 0,
  Down: 1,
  Left: 2,
  Right: 3,
} as const;

// It requires an extra line to pull out the values
type Direction = typeof ODirection[keyof typeof ODirection];
Enter fullscreen mode Exit fullscreen mode

But it's verbose to type. So here comes my uber-intelligence. Brace yourself, you might not be ready for it. Here we go:

export type RecordsValue<O> = O[Exclude<keyof O, undefined>]
// ...
type Direction = RecordValues<typeof ODirection>;
Enter fullscreen mode Exit fullscreen mode

Incredible.

Like if you want it to be part of native TS and save the planet. Or at least boost my ego. And of course feel free to share any improvement, I'm sure we all have it in our codebases somewhere ;)

Top comments (0)