capypad
0 day streak
typescript / expert
Snippet

Precise Validation with the 'satisfies' Operator

The 'satisfies' operator validates that an object matches a type without widening its inferred type. This allows you to keep specific literal information (like knowing 'red' is a tuple) while ensuring the object conforms to a general interface.

snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
type Colors = "red" | "green" | "blue";
type RGB = [number, number, number];
 
const palette = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255]
} satisfies Record<Colors, RGB | string>;
 
// palette.red is inferred as [number, number, number], not string | RGB
const redValue = palette.red[0];
Breakdown
1
satisfies Record<Colors, RGB | string>
Checks compatibility with the Record type without overwriting the specific inferred shapes of the properties.
2
palette.red[0]
Safe access is possible because 'satisfies' preserved the knowledge that 'red' is exactly an RGB tuple.