Sub topic 2
How `satisfies` Guides Inference
This chapter assumes basic TypeScript types, union types, object literals, and Record.
How `satisfies` guides inference
TypeScript often infers a useful, specific type for an expression. A type annotation can replace that inference with a broader declared type. The satisfies operator checks compatibility without replacing the inferred type.
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));The right side of satisfies gives the object a context. Each value must be either a string or an RGB tuple. At the same time, TypeScript remembers that green is a string and red is an RGB tuple. Therefore, these property-specific methods remain available.
Catching typos and excess properties
satisfies also performs excess property checking on an object literal. This catches a property that is probably a spelling mistake.
type Options = {
port: number;
host?: string;
};
const options = {
port: 80,
hots: "localhost",
} satisfies Options;
// Error: "hots" is not a property of OptionsA type assertion with as Options would silence this error. It tells TypeScript to trust the expression, so it is not a good replacement when you want validation.
> callout note > satisfies checks types only during compilation. It does not validate data received from JSON, a file, or a network at runtime.
Requiring every key with `Record`
Record<K, V> describes an object with keys K and values V. When K is a union, every key in that union is required.
type Color = "red" | "green" | "blue";
type RGB = [number, number, number];
const colors = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255],
} satisfies Record<Color, string | RGB>;A missing blue, an extra bleu, or a value with the wrong type produces a compile-time error.
Exercise
Why does satisfies Record<Color, string | RGB> help more than an annotation when using palette.green?
Show answer
It checks every key and value while preserving that green is specifically a string, so string methods remain available.