Sub topic 1
Inference and Annotations: A Quick Refresher
The satisfies operator exists because of a trade-off between two things you already use every day: type inference and type annotations. This chapter reviews how each one decides what type a variable has. The later chapters assume you know exactly where inference gives you precision and where an annotation takes it away.
Prerequisites
This chapter assumes you can already:
- Read and write basic TypeScript types, interfaces and type aliases.
- Use union types (
string | number) and literal types ("red"). - Work with object literals, arrays and tuples.
- Run the TypeScript compiler, or use an editor that shows types on hover.
You do not need to know satisfies yet. TypeScript 4.9 or later is required for it, but every example in this chapter works on older versions too.
Two ways a variable gets its type
TypeScript gives a variable its type in one of two ways:
- Inference. You write no type. The compiler looks at the initial value and works out a type.
- Annotation. You write the type yourself, after a colon:
const name: string = "Ada".
Both exist only at compile time. The compiler removes annotations when it produces JavaScript, so neither one changes what your program does when it runs.
const inferred = "Ada"; // the compiler decides the type
const annotated: string = "Ada"; // you decide the type
console.log(inferred, annotated);The difference lies in which side has the final say. With inference, the value decides the type. With an annotation, your declared type decides, and the value must fit it.
How inference works
Literal types for const, widened types for let
When you initialize a const with a primitive value, the compiler infers the exact literal type. A const can never be reassigned, so the narrowest type is safe. When you initialize a let, the compiler infers the general type, because the variable may later hold a different value of the same kind. Moving from a literal type to its general type is called widening.
const a = "hello";
let b = "hello";
const c = 42;
let d = 42;
type A = typeof a; // "hello"
type B = typeof b; // string
type C = typeof c; // 42
type D = typeof d; // numberYou can use typeof inside a type alias like this to check what the compiler inferred. Hovering over the name in your editor shows the same information.
Objects and arrays are widened inside
A const stops you from reassigning the variable. It does not stop you from changing the properties of an object stored in it. So the compiler widens each property of an object literal as if it were a let:
const settings = {
mode: "dark",
retries: 3,
};
type Settings = typeof settings; // { mode: string; retries: number }
settings.mode = "light"; // legal, so mode must be string
console.log(settings);If mode were inferred as "dark", the assignment on the next line would be an error. Widening keeps ordinary mutation working.
Arrays follow the same rule. The compiler infers one element type that covers all the elements:
const numbers = [1, 2, 3]; // number[]
const mixed = [1, "two", true]; // (string | number | boolean)[]
const point = [10, 20]; // number[], not a pairNotice the last line. A two-element array literal is inferred as an array of any length, not as a tuple. To get a tuple you need an annotation or as const, which comes up later in this chapter and in this tutorial.
Functions: parameters need types, return types are inferred
The compiler infers the return type of a function from its return statements. It does not infer parameter types from the body. Unless the function is passed somewhere that supplies the type (see contextual typing below), each parameter needs an annotation or it becomes an implicit any. With noImplicitAny on, which strict enables, that is an error.
function area(width: number, height: number) {
return width * height; // return type inferred as number
}
console.log(area(3, 4));Contextual typing
Sometimes the type comes from the place where an expression is used, not from the expression itself. This is contextual typing. A callback passed to map needs no annotation, because the compiler already knows what map will hand it:
const names = ["ada", "grace"];
const shouted = names.map((n) => n.toUpperCase()); // n is string
console.log(shouted);The same thing happens when you assign a function to a variable that has an annotated function type:
const double: (x: number) => number = (x) => x * 2; // x is number
console.log(double(21));The annotation on double supplies the context. The chapter on satisfies and contextual typing returns to this idea, because satisfies supplies context too.
The decision path
The diagram shows how the compiler picks the type of a variable declaration.
How annotations work
An annotation tells the compiler: "this variable has exactly this type, whatever the value looks like." The compiler then checks the initial value against that type and reports an error if it does not fit.
type Level = "debug" | "info" | "error";
const level: Level = "info"; // ok
// const bad: Level = "warn"; // Error: '"warn"' is not assignable to type 'Level'
console.log(level);You must write an annotation in these cases:
- Function parameters, unless contextual typing supplies them.
- Variables with no initializer, such as
let result: string;. - Empty collections, such as
const items: string[] = [];. Without the annotation the compiler cannot know what the array will hold. - Declared tuples, such as
const point: [number, number] = [10, 20];.
An annotation also helps in cases where you want an error at the declaration instead of at the use. If you write a function's return type, a mistake inside the function is reported on the return statement, not at some distant call site.
The annotation replaces the inferred type
The annotation does more than check the value. It becomes the type of the variable. The compiler stops using what it could have inferred from the initializer and uses what you wrote instead. When your annotation is broader than the value, the extra precision is lost.
type Id = string | number;
const box: { id: Id } = { id: "abc-123" };
// Error: 'toUpperCase' does not exist on type 'number'.
// console.log(box.id.toUpperCase());The value is clearly a string, but box.id has type Id because that is what you declared. The next chapter looks at this problem in detail. For now, remember the rule: an annotation trades precision for a guarantee about the shape.
Narrowing on assignment, and where it stops
There is one exception that often confuses people. When you annotate a variable with a union type, the compiler narrows it on the initial assignment, so the declared type is not the whole story for that variable:
const id: string | number = "abc-123";
console.log(id.toUpperCase()); // ok: narrowed to string by the assignment
let flexible: string | number = "abc-123";
console.log(flexible.toUpperCase()); // ok for now: narrowed to string
flexible = 42; // allowed, since the declared type is string | number
// flexible.toUpperCase(); // Error: now narrowed to numberThis narrowing applies only to the variable itself. It does not reach inside an object. In the box example above, the declared type of box is { id: Id }, and the compiler does not track that the id property happened to receive a string. Annotating a whole object or array therefore loses information about its parts, even though a simple annotated variable can keep it.
Inference without an annotation can also be too wide
Annotations are not the only source of lost precision. Inference widens too, and that matters when you pass a variable to something that expects specific literals.
type Shape = { kind: "circle" | "square" };
function draw(shape: Shape) {
console.log(`drawing a ${shape.kind}`);
}
draw({ kind: "circle" }); // ok: the literal is checked in place
const shape = { kind: "circle" }; // inferred as { kind: string }
// draw(shape); // Error: Type 'string' is not assignable to type '"circle" | "square"'.The first call works because the object literal appears directly in the argument position, where the parameter type provides context and "circle" stays a literal. The second case fails because shape was widened to { kind: string } at its declaration, before it ever reached draw.
The usual fixes are:
| Fix | Example | What you give up |
|---|---|---|
| Annotate the variable | `const shape: Shape = { kind: "circle" }` | The variable now has exactly the type `Shape` and nothing more specific. |
| Use `as const` | `const shape = { kind: "circle" } as const` | The object becomes deeply `readonly`. |
| Inline the literal | `draw({ kind: "circle" })` | You cannot reuse the object elsewhere. |
Each option solves the immediate problem and has a cost. The rest of this tutorial is about a fourth option that avoids some of those costs.
Practical guidance for annotations
A few habits cover most real code:
- Let inference do the work for local variables.
const total = prices.reduce(...)needs no annotation, and an annotation only adds noise. - Annotate function parameters and the public surface of modules. Exported functions and types are contracts, and writing the types explicitly keeps the contract from changing by accident when the body changes.
- Annotate when you want the compiler to enforce a shape. If a value must be a
Config, say so, so a wrong value is reported at the declaration. - Check what was inferred before you annotate. Hover or use
typeofin a type alias. Often the inferred type is already what you wanted.
Common errors in this area
- Assuming
constfreezes an object. It only prevents reassigning the variable. Properties stay mutable, so the compiler widens them. - Expecting a tuple from an array literal.
const pair = [1, 2]isnumber[]. Annotate it as[number, number]if the length matters. - Annotating "to be safe" and losing precision. A broad annotation such as
Record<string, string | number>accepts any key and forgets which value is a string. Later code then needs extra checks. - Reading narrowing as persistent. Assignment narrowing lasts only until the variable is reassigned or a function boundary intervenes, and it does not apply to properties of an annotated object.
- Relying on implicit
any. A parameter with no annotation and no context becomesany, which switches off checking for everything that touches it.
Where this leads
You now have the two ingredients of the problem:
- Inference keeps precise types but checks nothing about the shape you intended.
- Annotations check the shape but replace the precise types with the declared ones.
You can always get one of these two properties, and sometimes you need both at once. The next chapters show what goes wrong when an annotation widens a configuration object, why an as assertion does not solve it, and how satisfies checks a value against a type while leaving the inferred type alone.
Exercise
Given the code below, what is the type of config.mode, and what is the type of fixed? Then say what the compiler does with the commented line and why.
const config = { mode: "dark" };
const fixed = "dark";
// const theme: "dark" | "light" = config.mode;
Show answer
config.mode is string, because the compiler widens properties of an object literal (they can be reassigned). fixed is the literal type "dark", because it is a const initialized with a primitive. The commented line would be an error: string is not assignable to "dark" | "light". Assigning fixed instead would compile. To make config.mode a literal you could write const config = { mode: "dark" } as const;, or annotate config with a type whose mode is "dark" | "light", though the annotation would give up the narrower "dark" type.
Exercise
Why does this code compile for id but fail for box.id, even though both hold the string "abc"?
const id: string | number = "abc";
id.toUpperCase();
const box: { id: string | number } = { id: "abc" };
box.id.toUpperCase();
Show answer
A variable annotated with a union type is narrowed to the assigned type on initialization, so id is treated as string and toUpperCase is allowed. Narrowing by assignment applies to the variable itself, not to properties inside an annotated object. The declared type of box is { id: string | number }, so box.id is string | number, and toUpperCase does not exist on the number member of the union. The compiler reports an error on the last line.
Exercise
Write a declaration for a variable origin so that its type is the tuple [number, number], and say why const origin = [0, 0] is not enough.
Show answer
const origin: [number, number] = [0, 0];. Without the annotation, the compiler infers number[] from an array literal, which allows any length. An annotation (or as const, which would produce readonly [0, 0]) is needed to get a fixed-length tuple type.