Sub topic 1
Inference and annotations: a quick refresher
TypeScript often knows more about a value than you explicitly write. It uses type inference, which means it derives a type from the value or surrounding code. A type annotation is a type you write yourself to describe what a variable, parameter, property, or return value should accept.
This chapter assumes you already know basic TypeScript types, interfaces, type aliases, unions, literal types, object literals, arrays, tuples, Record, and keyof.
Prerequisites
You should be able to:
- Read and write type aliases and interfaces.
- Use union types such as
"draft" | "published". - Create object literals and arrays.
- Understand the difference between a value and its static type.
- Recognize basic type inference and type annotations.
TypeScript infers types from values
When you initialize a variable, TypeScript usually infers its type from the initializer.
const count = 3;
const message = "ready";
const enabled = true;
console.log(count, message, enabled);Here, TypeScript knows that count is a number, message is a string, and enabled is a boolean. You do not need to write those annotations.
Inference can also preserve a literal type in some situations. A literal type describes one exact value, such as "draft" or 3.
const status = "draft";
let editableStatus = "draft";
console.log(status, editableStatus);The const variable cannot be reassigned, so TypeScript can treat status as the literal type "draft". The let variable can later receive another string, so TypeScript usually infers editableStatus as string.
type Status = "draft" | "published";
const current: Status = "draft";
let next: Status = "draft";
next = "published";
console.log(current, next);The annotation : Status tells TypeScript that both variables may contain either allowed value. It also rejects values outside the union.
Object inference is often wider
Object literals show an important difference. TypeScript usually widens mutable-looking object properties, even when the object itself is stored in a const variable.
const settings = {
mode: "development",
retries: 3,
};
settings.mode = "production";
settings.retries = 4;
console.log(settings);The variable binding settings cannot be replaced, but its properties can be changed. TypeScript therefore commonly infers:
settings.modeasstringsettings.retriesasnumber
The inferred type is similar to this:
{
mode: string;
retries: number;
}The property mode is not inferred as only "development" because the property can be assigned another string later.
If the object must use a fixed set of values, an annotation can express that requirement.
type Settings = {
mode: "development" | "production";
retries: number;
};
const settings: Settings = {
mode: "development",
retries: 3,
};
settings.mode = "production";
console.log(settings.mode, settings.retries);Now TypeScript checks the object against Settings. It rejects "testing" for mode, but it sees the property as the union "development" | "production" rather than only the initial literal "development".
Annotations control the variable's type
An annotation does more than document a value. It controls the static type that TypeScript uses for later expressions.
type Result = {
value: string | number;
};
const result: Result = {
value: "complete",
};
console.log(result.value);The actual value is currently a string. However, the declared type says that result.value may be a string or a number. Code using result.value must account for both possibilities.
type Result = {
value: string | number;
};
const result: Result = {
value: "complete",
};
if (typeof result.value === "string") {
console.log(result.value.toUpperCase());
} else {
console.log(result.value.toFixed(2));
}The typeof check is a type guard. It narrows a union type to a more specific type inside a branch.
This behavior is useful when you want an API boundary to have a stable, explicit type. It can also remove useful details that inference had preserved. The next chapters use this distinction to explain why an ordinary annotation can be too broad for a configuration object.
Context can guide inference
Sometimes TypeScript uses the expected type around an expression to infer more precise values. This is called contextual typing.
Function parameters are a common example:
const names = ["Ada", "Grace", "Lin"];
names.forEach((name) => {
console.log(name.toUpperCase());
});TypeScript knows that name is a string because forEach expects a callback whose parameter receives an array element.
An object can also receive context from an annotation:
type ServerOptions = {
host: string;
port: number;
};
const options: ServerOptions = {
host: "localhost",
port: 8080,
};
console.log(`${options.host}:${options.port}`);The expected type checks each property while the object literal is created. This catches incompatible values early, but the resulting variable is still viewed through the declared ServerOptions type.
A simple model for the next chapter
When you read TypeScript code, ask two separate questions:
- What type does TypeScript infer for this expression?
- What type, if any, does the surrounding annotation require?
The first question concerns precision. The second concerns validation and the type exposed to later code.
| Situation | Main effect |
|---|---|
| No annotation | TypeScript infers a type from the expression |
| Type annotation | TypeScript checks the value and uses the declared type |
| Contextual type | The surrounding type guides inference while checking the expression |
The satisfies operator is designed for cases where you want the second effect, validation against a known type, without unnecessarily losing the first effect, precise inference.
Exercise
What are the usual inferred types of const value = "open" and const box = { value: "open" }, and why can they differ?
Show answer
value is usually inferred as the literal type "open" because the const binding cannot be reassigned. box.value is usually inferred as string because the object property can be changed later, even though the box binding is const.