patterntypescriptnoneTip
satisfies Operator: Validate Without Losing Inference
Viewed 0 times
TypeScript 4.9+
satisfies operatortype validationinference preservationTypeScript 4.9
Error Messages
Problem
Using a type annotation on an object literal validates the shape but loses specific literal types. Using 'as Type' skips validation entirely. There was no middle ground.
Solution
Use the 'satisfies' operator to validate a value against a type while keeping the inferred literal types.
type Config = Record<string, string | number>;
// BAD: annotation loses literal types
const cfg1: Config = { port: 3000, env: 'prod' };
cfg1.port.toFixed(); // Error: 'string | number' has no 'toFixed'
// GOOD: satisfies validates + keeps inferred types
const cfg2 = { port: 3000, env: 'prod' } satisfies Config;
cfg2.port.toFixed(); // OK — TypeScript knows it's number
cfg2.env.toUpperCase(); // OK — TypeScript knows it's stringWhy
Type annotations widen the inferred type to exactly the annotated type. 'satisfies' is a type-level assertion that checks compatibility but does not change the inferred type of the expression.
Gotchas
- satisfies does not narrow the type of the variable — it only validates at the point of use.
- If the value fails the satisfies check, you get a compile error, not a runtime error.
- Available only in TypeScript 4.9+.
Revisions (0)
No revisions yet.