typestar

Literal and union types in TypeScript

A literal type is one exact value; a union is a closed set of them.

type Theme = "default" | "monokai" | "dracula";
type Stars = 0 | 1 | 2 | 3;

const THEMES = ["default", "monokai", "dracula"] as const;
type FromArray = (typeof THEMES)[number];

const LIMITS = { short: 30, long: 300 } as const;
type LimitName = keyof typeof LIMITS;
type LimitValue = (typeof LIMITS)[LimitName];

function apply(theme: Theme, stars: Stars): string {
  return `${theme}:${stars}`;
}

const chosen: FromArray = "monokai";
const named: LimitName = "short";
const seconds: LimitValue = LIMITS[named];
console.log(apply(chosen, 3), seconds);

How it works

  1. as const narrows an object's values to their literals.
  2. A union of literals is how TypeScript writes an enum without one.
  3. typeof on a const object recovers the union from the values.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
551
Tokens
141
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 100 seconds.

Type this snippet

Step 2 of 4 in Primitives & literals, step 2 of 23 in Types & annotations.

← Previous Next →