typestar

Enums and const assertions in TypeScript

Fixed sets of values, as enums or literal unions.

enum Status {
  Pending = "pending",
  Active = "active",
  Closed = "closed",
}

const ORDER = ["low", "medium", "high"] as const;
type Priority = (typeof ORDER)[number];

function label(status: Status, priority: Priority): string {
  return `${status}/${priority}`;
}

const current = label(Status.Active, "high");
const all = Object.values(Status);

How it works

  1. A string enum names each member's value.
  2. as const freezes an array of literals.
  3. (typeof ORDER)[number] derives a union from it.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
343
Tokens
88
Three-star pace
85 tpm

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

Type this snippet

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

← Previous Next →