Emmanuel Akinfulubi

TypeScriptBasic

Enum vs union type in TypeScript

9 An enum of colours, and the better alternative

fair

Define a set of four colours and a variable that can only hold one of them. Do it with an enum, then do it again with as const, and compare what each costs.

Stuck? Three hints, smallest first
  1. 1. enum Colour { Red, Green } gives its members the numbers 0 and 1 unless you assign values.
  2. 2. An enum is not erased. It emits real JavaScript, and Node refuses to run it without a compile step.
  3. 3. const COLOURS = [...] as const plus (typeof COLOURS)[number] gives you the same safety and disappears at runtime.

The answer, and proof it works

const same = (a: unknown, b: unknown): boolean =>
  JSON.stringify(a) === JSON.stringify(b);

function test(name: string, got: unknown, want: unknown): void {
  console.log(
    (same(got, want) ? 'ok   ' : 'FAIL ') + name +
    (same(got, want) ? '' : `  got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
  );
}

// The enum version.
enum Colour {
  Red = 'red',
  Green = 'green',
  White = 'white',
  Blue = 'blue',
}

let selectedColour: Colour = Colour.Green;
selectedColour = Colour.Blue;

// The version that leaves nothing behind.
const COLOURS = ['red', 'green', 'white', 'blue'] as const;
type ColourName = (typeof COLOURS)[number];   // 'red' | 'green' | 'white' | 'blue'

let picked: ColourName = 'green';
picked = 'blue';

// Both reject nonsense:
// selectedColour = 'purple';   // not assignable to Colour
// picked = 'purple';           // not assignable to ColourName

console.log('enum value:', selectedColour);
console.log('literal union value:', picked);
console.log('all colours:', COLOURS.join(', '));

test('enum member holds its string', selectedColour, 'blue');
test('union member holds its string', picked, 'blue');
test('the array is the single source of truth', COLOURS.length, 4);
test('membership check', COLOURS.includes(picked), true);

Output


      

Both are safe. The difference is what survives compilation. The enum becomes a real object in your output, so it adds bytes and cannot be run by node file.ts directly. The as const array plus (typeof COLOURS)[number] gives the same checking, and the type vanishes entirely. Reach for the second unless you need an enum for a library’s sake.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.