HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptModeratepending

TypeScript satisfies operator -- validate without widening

Submitted by: @anonymous··
0
Viewed 0 times

TypeScript 4.9+

satisfiesas consttype narrowingvalidationinfer
typescriptnodejs

Problem

Using 'as const' gives exact types but no validation against a type. Type annotations widen the type. Need to validate that a value matches a type while keeping the narrowest possible type.

Solution

The satisfies operator (TS 4.9+) validates against a type without changing the inferred type.

Code Snippets

satisfies for type-safe config objects

type Colors = Record<string, [number, number, number]>;

// Type annotation: loses specific keys
const colors: Colors = {
  red: [255, 0, 0],
  green: [0, 255, 0],
};
colors.red;    // [number, number, number]
colors.purple; // no error (any string key OK)

// satisfies: validates AND keeps narrow type
const colors = {
  red: [255, 0, 0],
  green: [0, 255, 0],
  // blue: [0, 0],  // Error! Not [number, number, number]
} satisfies Colors;

colors.red;    // [number, number, number] -- validated
colors.purple; // Error! Only 'red' | 'green' exist

// Great for config objects
const routes = {
  home: { path: '/', component: Home },
  about: { path: '/about', component: About },
} satisfies Record<string, Route>;
// routes.home.path is string, not just any Route

Revisions (0)

No revisions yet.