Sub topic 16
Validating without widening using satisfies
This chapter assumes you can write type annotations, know that const and let infer different types, and can write object and union types. You should also be able to run tsc or use an editor with TypeScript support.
The problem with annotations
An annotation checks a value against a type, but it also replaces the value's inferred type with the annotated one. Compare these two versions:
type Palette = Record<string, string | number[]>;
const colors: Palette = {
red: [255, 0, 0],
green: "#00ff00",
};
colors.red.map((channel) => channel / 255);
// Error: Property 'map' does not exist on type 'string | number[]'.The annotation accepts the object, but colors.red is now typed as string | number[]. The compiler has forgotten that red is an array, so the call to map fails.
Using satisfies
The satisfies operator checks that an expression matches a type, and it leaves the expression's own type unchanged:
type Palette = Record<string, string | number[]>;
const colors = {
red: [255, 0, 0],
green: "#00ff00",
} satisfies Palette;
const scaled = colors.red.map((channel) => channel / 255);
console.log(scaled); // [1, 0, 0]Here colors.red stays number[], so map works. The object is still checked against Palette, so a value that does not fit the type is still an error.
Checking also catches missing and misspelled properties:
type Theme = { primary: string; secondary: string };
const theme = {
primary: "#ffffff",
secondary: "#000000",
} satisfies Theme;
console.log(theme.primary.toUpperCase()); // #FFFFFF
// const broken = { primary: "#fff", secondry: "#000" } satisfies Theme;
// Error: Property 'secondary' is missing.Choosing between annotation and satisfies
| Approach | Checks the value | Keeps precise property types | Good for |
|---|---|---|---|
| Annotation `: Type` | Yes | No, widens to `Type` | Function parameters and values with one known shape |
| `satisfies Type` | Yes | Yes | Config and lookup objects you read later |
| No check | No | Yes | Local values where inference is enough |
Use satisfies when you want validation and the inferred detail that comes with it. Use an annotation when callers should only see the declared type.
Common errors
- Adding an annotation to a config object and then losing the array or literal types you need.
- Expecting
satisfiesto change a variable's type. It only checks the expression. - Writing
satisfieson a value that is later reassigned. Reassignment is checked against the variable's inferred type, which may be wider than you expect.
Exercise
Given const sizes = { small: 1, large: 3 } satisfies Record<string, number>;, what is the type of sizes.small?
Show answer
number. The satisfies check passes, and the property keeps its inferred type. Because the object is not declared with as const, the literal 1 widens to number.