TypeScript satisfies Operator
Today I learned about the 'satisfies' operator in TypeScript and how it improves type checking while maintaining type inference.
What I Learned
The 'satisfies' operator allows you to validate that a value matches a type without widening the inferred type.
Example Usage
type ColorMap = {
[K: string]: [number, number, number]
}
// Without satisfies
const colors = {
red: [255, 0, 0],
green: [0, 255, 0],
blue: [0, 0, 255]
} // Type is inferred but not validated against ColorMap
// With satisfies
const colors2 = {
red: [255, 0, 0],
green: [0, 255, 0],
blue: [0, 0, 255]
} satisfies ColorMap
// Type is both inferred AND validated
Benefits
- Catches type errors at declaration
- Preserves literal types
- Better autocomplete support
- No type widening
This operator is particularly useful when working with configuration objects and type-safe APIs.