Sub topic 5
How satisfies guides inference
This chapter assumes you know basic TypeScript types, union and literal types, and how Record works. It also assumes you have seen the satisfies syntax from the previous chapters. Here you will learn the second job of satisfies. It does not only check an expression. It also hands the target type to the compiler as a hint while it infers the expression's type.
Two jobs, one operator
So far satisfies has been described as a check: the expression must be assignable to a type, and the variable keeps its own inferred type. That is accurate but incomplete. The compiler does not infer the type first and compare afterwards. The type after satisfies takes part in the inference itself.
This hint is called the contextual type. TypeScript already uses contextual types in many places. In [1, 2, 3].map((n) => n * 2), the parameter n has no annotation, but TypeScript knows it is a number because map expects a callback over the array's element type. The type expected at a position is the context, and it fills in what you left out.
With satisfies, the type on the right acts as the context for the whole expression on the left. The compiler then does two things:
- It infers the type of the expression, using the target type as context.
- It checks that the inferred type is assignable to the target type.
The variable gets the type from step 1, not the target type itself.
Correction: the diagram must be in the required fence format. Here it is in the right form:
The rest of the chapter looks at what the contextual type changes in practice. There are four effects:
- Callback parameters get types without annotations.
- Literal values keep their literal types.
- Array literals can become tuples.
- Return types of callbacks stay specific.
Typing callback parameters without annotations
Suppose you have a table of event handlers. Every handler receives the same kind of event. Without any context, an unannotated callback parameter is an error under strict:
type PointerEvent2D = { x: number; y: number };
type Handler = (event: PointerEvent2D) => void;
// Error: Parameter 'event' implicitly has an 'any' type.
// const untyped = {
// click: (event) => console.log(event.x + event.y),
// };
const handlers = {
click: (event) => console.log(event.x + event.y),
move: (event) => console.log(event.x),
} satisfies Record<string, Handler>;
handlers.click({ x: 1, y: 2 }); // prints 3
handlers.move({ x: 5, y: 0 }); // prints 5Record<string, Handler> tells the compiler that every property value should be a Handler. For each arrow function, the compiler reads the contextual signature (event: PointerEvent2D) => void and gives event the type PointerEvent2D. You wrote no annotation, and autocomplete on event. works.
The variable handlers still has the specific type with the keys click and move. If you had annotated it as Record<string, Handler>, any key would be accepted, so handlers.clik would compile. With satisfies, a misspelled key is an error.
A type annotation on the variable gives the same contextual typing for the parameters. The difference is only in what the variable becomes afterwards. That is the pattern in this chapter: the context is the same, and the result type differs.
Return types stay specific
Contextual typing flows into parameters. It does not overwrite the return type that the compiler infers from the function body. This matters when the target type is loose about what a callback returns.
type Parser = (input: string) => unknown;
const parsers = {
int: (input) => parseInt(input, 10),
trim: (input) => input.trim(),
} satisfies Record<string, Parser>;
const n: number = parsers.int("42");
const s: string = parsers.trim(" hi ");
console.log(n + 1, s.toUpperCase()); // 43 HIParser says the result is unknown. Each callback must be assignable to Parser, and (input: string) => number is assignable because number is assignable to unknown. The variable keeps the more precise types. So parsers.int("42") is a number, and you can assign it to const n: number without a cast.
With an annotation, const parsers: Record<string, Parser>, both calls would return unknown. You would have to narrow or assert before using the results.
Keeping literal types
When TypeScript infers the type of a mutable position, such as an object property, it normally widens a literal to its base type. This is why { dir: "left" } has the type { dir: string }. That widening is what breaks the call in this example:
type Direction = "left" | "right";
type MoveOptions = { dir: Direction; steps: number };
function go(options: MoveOptions): string {
return `${options.steps} steps ${options.dir}`;
}
const widened = { dir: "left", steps: 2 };
// Error: Type 'string' is not assignable to type 'Direction'.
// go(widened);
const move = { dir: "left", steps: 2 } satisfies MoveOptions;
console.log(go(move)); // 2 steps left
const exactDir: "left" = move.dir; // compiles: dir is "left", not stringWidening is skipped when the contextual type at that position contains literal types. Here the context for dir is Direction, a union of string literals, so the compiler keeps "left". The type of move is { dir: "left"; steps: number }. It is checked against MoveOptions, and it can be passed to go directly.
Note what did not happen. steps is still number, not 2, because the context for that property is plain number, which holds no literal types. Literals survive only where the context asks for literals. This is different from as const, which freezes every value. The next chapters return to that combination.
Tuples instead of arrays
An array literal is normally inferred as an array: [3, 4] is number[]. If the contextual type is a tuple, the compiler infers a tuple.
type Point = [number, number];
const loose = [3, 4]; // number[]
const point = [3, 4] satisfies Point; // [number, number]
const [x, y] = point;
console.log(x + y); // 7A shorter or longer array literal now fails the check instead of silently becoming a number[]. For example, [3, 4, 5] satisfies Point is an error because the tuple has three elements.
Unions and discriminated unions
The contextual type can be a union. For object literals, the compiler uses the discriminating property to pick the matching member and applies that member's property types as context.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
const shapes = [
{ kind: "circle", radius: 2 },
{ kind: "square", side: 3 },
] satisfies Shape[];
for (const shape of shapes) {
if (shape.kind === "circle") {
console.log(Math.PI * shape.radius ** 2);
} else {
console.log(shape.side ** 2);
}
}Because kind keeps its literal types, "circle" and "square", the if narrows each element. Without the context, kind would widen to string and the narrowing would not work. The array literal also would not be accepted as Shape[] later, since string is not a valid kind.
A typo in a discriminant is caught. Writing { kind: "circel", radius: 2 } is an error, because no member of Shape has that kind.
What the context changes
| Position in the expression | Without context | With `satisfies` context |
|---|---|---|
| Unannotated callback parameter | Implicit `any` error under `strict` | Typed from the contextual signature |
| String or number property | Widened to `string` or `number` | Kept as a literal if the context holds literal types |
| Array literal | `T[]` | A tuple if the context is a tuple type |
| Callback return type | Inferred from the body | Still inferred from the body, not replaced by the target's return type |
| Extra or misspelled property | Accepted | Reported (see the next chapter) |
Context is only as good as the target type
The hint works only if the target type contains the information. Two common ways to lose it:
// Error: Parameter 'input' implicitly has an 'any' type.
// const noHint = {
// shout: (input) => input.toUpperCase(),
// } satisfies Record<string, unknown>;
const withHint = {
shout: (input) => input.toUpperCase(),
} satisfies Record<string, (input: string) => string>;
console.log(withHint.shout("hi")); // HIunknown says nothing about function parameters, so the compiler has no signature to copy. The check itself would pass, since any function is assignable to unknown, but the parameter is untyped. If you see an implicit any error inside a satisfies expression, look at the target type first.
A related limit: a contextual type from a union of function types works only when the compiler can combine the signatures. If the union members take different parameter types, you may still get an implicit any. In that case, annotate the parameter yourself, and satisfies will check the result.
Checking what you got
You can see the inferred type in your editor by hovering over the variable. You can also verify it in code with an assignment that only compiles if the type is precise enough. This is the technique used above with const exactDir: "left" = move.dir. A small helper makes this repeatable:
type Equal<A, B> =
(<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2)
? true
: false;
const config = { mode: "fast", retries: 3 } satisfies {
mode: "fast" | "safe";
retries: number;
};
const check: Equal<typeof config, { mode: "fast"; retries: number }> = true;
console.log(check); // trueIf the compiler had widened mode to string, the assignment = true would be an error, because Equal would resolve to false.
Common mistakes
- Expecting
satisfiesto change the declared type of a variable later. It only affects the type inferred at the point of the expression. After that, the variable is an ordinaryconstwith that inferred type. - Assuming every property becomes a literal. Only positions whose context contains literal types keep them. Use
as constwhen you want all values frozen. - Writing a vague target type such as
Record<string, unknown>and then wondering why callback parameters areany. - Assuming that a callback's return type is checked against the target's return type only. It is checked for assignability, but the variable keeps the narrower inferred return type. This is usually what you want, but it means the variable's type can be more specific than the type you wrote.
Exercise
The code below fails to compile. Why does satisfies fix the call to paint, and what is the type of style.align after the fix?
type Align = "start" | "end";
function paint(style: { align: Align; size: number }) {}
const style = { align: "start", size: 12 };
paint(style); // error
Show answer
Without a context, the compiler widens the property align to string, and string is not assignable to Align, so the call fails. Writing const style = { align: "start", size: 12 } satisfies { align: Align; size: number }; gives the property align the contextual type Align, which contains literal types. The compiler therefore keeps the literal and infers { align: "start"; size: number }. After the fix, style.align has the type "start", and paint(style) compiles.
Exercise
What are the types of a and b in the code below, and why does the second one differ from what an annotation Record<string, Fn> would give?
type Fn = (value: number) => unknown;
const fns = {
a: (value) => value * 2,
b: (value) => String(value),
} satisfies Record<string, Fn>;
Show answer
fns.a has the type (value: number) => number and fns.b has the type (value: number) => string. The parameter value is typed as number from the contextual signature of Fn. The return types come from the function bodies, not from the unknown in Fn. With the annotation const fns: Record<string, Fn>, both properties would have the type Fn, so each call would return unknown.