How to validate an object in TypeScript with satisfies without losing exact field typesBrief · digest for November 24
Brief≈ 2 min

How to validate an object in TypeScript with satisfies without losing exact field types

Suppose you define a color palette where one field is a hex string and another is an RGB tuple. You add Record<Color, string | RGB> (a dictionary with strict keys and union values). The compiler catches key typos, yet forgets that green is specifically a string and widens it to string | RGB. Calling toUpperCase() without a typeof check fails.

TypeScript 4.9 introduced the satisfies operator to fix this. It checks the object against a type while preserving each property's narrow inferred type:

type Color = "red" | "green" | "blue";
type RGB = [number, number, number];

// Annotation widens green to string | RGB — toUpperCase() fails
const bad: Record<Color, string | RGB> = {
  red: [255, 0, 0],
  green: "#00ff00",
  blue: [0, 0, 255],
};

// satisfies catches a key typo (bleu) and keeps exact field types
const palette = {
  red: [255, 0, 0],
  green: "#00ff00",
  blue: [0, 0, 255],
} satisfies Record<Color, string | RGB>;

// The compiler knows green is a string and red is a number tuple
const upper = palette.green.toUpperCase();
const red = palette.red[0];

This works great for configs, routes, and design tokens. Unlike as, satisfies never hides structural errors, and as const satisfies freezes values as well. Remember it disappears when compiled to JS, so don't rely on it to validate external API responses.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 2