Sub topic 1
The TypeScript `satisfies` Operator: Validate Types Without Widening
Prerequisites
Assume you know basic TypeScript types, union types, object literals, type inference, and type annotations. You should also know that Record<K, V> describes an object with keys K and values V.
Inference and annotations: a quick refresher
TypeScript often infers a type from a value:
const color = "green"; // type: "green"A type annotation tells TypeScript what type a variable must have:
const color: string = "green"; // type: stringThe annotation is wider than the inferred literal type. It describes more possible values, so TypeScript forgets that this particular value is exactly "green".
The problem: annotations throw away precision
This matters when object properties have different, useful types:
type Color = "red" | "green" | "blue";
type RGB = [number, number, number];
const palette: Record<Color, string | RGB> = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255],
};
// Error: green is treated as string | RGB.
// palette.green.toUpperCase();The annotation validates the whole object, but it widens every property to string | RGB. You must narrow the value before using it.
Why `as` assertions are not a fix
A type assertion uses as to tell TypeScript to treat a value as a type:
type Options = { port: number; host?: string };
const options = { port: 80, hots: "localhost" } as Options;This assertion hides the misspelled hots property. It does not validate the object in the same way an annotation does. Use assertions only when you have information that TypeScript cannot infer, and you have verified that information yourself.
Meet `satisfies`: check without widening
The satisfies operator checks assignability while preserving the expression's inferred type. It was added in TypeScript 4.9.
type Color = "red" | "green" | "blue";
type RGB = [number, number, number];
const palette = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255],
} satisfies Record<Color, string | RGB>;
console.log(palette.green.toUpperCase());
console.log(palette.red.map((value) => value * 2));Here, satisfies checks the keys and values. It still knows that green is a string and red is an RGB tuple.
Exercise
Which operator should you use to validate an object against a type while keeping precise property types?
Show answer
Use satisfies.