Skip to content

Instantly share code, notes, and snippets.

@bbarry
Created July 15, 2020 13:28
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 bbarry/8bdca698967ce131d341b41fe9228a15 to your computer and use it in GitHub Desktop.
Save bbarry/8bdca698967ce131d341b41fe9228a15 to your computer and use it in GitHub Desktop.
typescript building a better enum
// https://github.com/krzkaczor/ts-essentials
import { Opaque } from 'ts-essentials';
export const DIRECTIONS = {
UP: 'Up' as Opaque<'Up', 'DIRECTIONS'>,
DOWN: 'Down' as Opaque<'Down', 'DIRECTIONS'>,
} as const;
export type DIRECTIONS = typeof DIRECTIONS[keyof typeof DIRECTIONS];
// these are valid usages
const d1: DIRECTIONS = DIRECTIONS.UP;
const d2: DIRECTIONS = "Up" as DIRECTIONS;
// these cause compile errors
// @ts-expect-error
const d3: DIRECTIONS = "Up";
// @ts-expect-error
const d4: DIRECTIONS = "PLASTICS";
/*
const d5: DIRECTIONS = // Autocompletes: DIRECTIONS.UP, DIRECTIONS.DOWN
This is a little more complex than https://medium.com/@maxheiber/alternatives-to-typescript-enums-50e4c16600b1
but it fixes the TS autocomplete concern
compiles as (ES6+; earlier gets var instead of const):
export const DIRECTIONS = {
UP: 'Up',
DOWN: 'Down',
};
// these are valid usages
const d1 = DIRECTIONS.UP;
const d2 = "Up";
// @ts-expect-error
const d3 = "Up";
// @ts-expect-error
const d4 = "PLASTICS";
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment