Skip to main content

Command Palette

Search for a command to run...

Typescript - get Type from object with `as cons` syntax and use it like an enum type

Published
1 min read
L

I am a developer from Vietnam.

Typescript - get Type from object with as cons syntax and use it like an enum type

You can read more about Objects vs Enums at TypeScript's document: https://www.typescriptlang.org/docs/handbook/enums.html#objects-vs-enums.

Document's example:

const enum EDirection {
  Up,
  Down,
  Left,
  Right,
}

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

EDirection.Up;
// EDirection.Up = 0

ODirection.Up;
// ODirection.Up = 0

// Using the enum as a parameter
function walk(dir: EDirection) {}

To get Type from object with as cons syntax and use it like an enum type, just do like document's example:

type Direction = (typeof ODirection)[keyof typeof ODirection];

function run(dir: Direction) {}

More from this blog

Vietnamese / Ja / En  🧑‍💻 blog

155 posts

Vietnamese developer 🧑‍💻