Satisfies Checks Readonly Sort Tables

Verify a lookup table against a target shape with satisfies while keeping literal narrowing, so missing or misnamed rows fail at compile time.

TypescriptData Integrity

Code

typescriptsnippet
25 lines
type Priority = 'now' | 'soon' | 'later';

// satisfies validates against PriorityTable while keeping exact literals:
// the variable keeps its own narrower type instead of widening.
const priorities = {
  now: { rank: 0, label: 'drop everything' },
  soon: { rank: 1, label: 'this week' },
  later: { rank: 2, label: 'backlog' },
} satisfies Readonly<Record<Priority, { rank: number; label: string }>>;

// Literal types survive: this reads as 0 | 1 | 2, not number.
type Rank = (typeof priorities)[Priority]['rank'];
const rank: Rank = priorities.now.rank;
console.log('now rank:', rank);

// The table is exhaustively checked: adding 'urgent' to the union below
// breaks compilation until a row exists for it — swap the comment to see:
// type Priority2 = Priority | 'urgent';
// type Strict = Readonly<Record<Priority2, { rank: number; label: string }>>;
// const _wider: Strict = priorities; // error names 'urgent' as missing

// Sorting stays correct: rank comes from checked rows, not guesses.
const order = (Object.keys(priorities) as Priority[])
  .sort((a, b) => priorities[a].rank - priorities[b].rank);
console.log('order:', order.join(' < '));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

now rank: 0
order: now < soon < later

Inside the snippet

Under the hood: the function order.

What to watch for

  • All that is required beforehand is the language toolchain.

Putting it to use

Entry signature: const order = (Object.keys(priorities)

The demo output is labeled (now rank:, order:), so every printed line maps back to a specific operation.

Core lines

.sort((a, b) => priorities[a].rank - priorities[b].rank);

Interactive Tools for This Topic

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `order` at load time.