Sub topic 2
What the compiler infers for you
This chapter assumes you know JavaScript functions, TypeScript primitive, object, array, and union types, and how to run TypeScript with tsc or an editor.
TypeScript inference is the compiler's process for calculating a type when you do not write one explicitly. Inference reduces repetition while keeping your code checked. You should still annotate public boundaries when an explicit contract makes the code easier to understand.
Inference from values and returns
When TypeScript can see the value assigned to a variable, it usually infers a suitable type.
const count = 3; // number
const title = "Report"; // string
const enabled = true; // boolean
const scores = [10, 20]; // number[]
function square(value: number) {
return value * value;
}
// The return type is inferred as number.For a function, TypeScript checks every reachable return statement and combines the results. If the branches return different types, the result is usually a union.
function formatId(id: number, detailed: boolean) {
if (detailed) {
return { text: `ID-${id}`, numeric: id };
}
return `ID-${id}`;
}
// The inferred return type is
// { text: string; numeric: number } | stringAn explicit return annotation can document an intended contract or reveal a mistake sooner.
function double(value: number): number {
return value * 2;
}The annotation is unnecessary here, but useful when readers need to know the function's promise without reading its body.
Contextual typing
Inference can also flow into an expression from the place where that expression is used. This is called contextual typing. A callback receives its parameter type from the function that accepts it.
const names = ["Ada", "Grace", "Linus"];
const longNames = names.filter(name => name.length >= 5);
// `name` is inferred as string.
// `longNames` is inferred as string[].The same rule applies to event handlers, configuration objects, and function arguments.
const numbers = [1, 2, 3];
numbers.map((value, index) => `${index}: ${value}`);
// value is number, index is number, result is string[]You do not need to annotate value or index. Adding an annotation is valid, but it repeats information that the surrounding function already provides.
Widening and literal types
TypeScript often widens a literal type to its broader primitive type. A mutable variable must be able to receive another value later.
let status = "pending"; // string
status = "complete"; // allowed
const fixedStatus = "pending"; // "pending"A const variable cannot be reassigned, so TypeScript can preserve its literal type. However, properties inside a normal object or elements inside a normal array are usually widened because they remain mutable.
const settings = {
mode: "dark",
retries: 3
};
// mode is string, and retries is number.
settings.mode = "light"; // allowedUse as const when the complete value should be treated as deeply read-only with literal types.
const route = {
method: "GET",
path: "/users"
} as const;
// method is "GET", and path is "/users".Do not use as const merely to silence an error. It changes mutability and can make later updates invalid.
Inference failures and explicit annotations
A parameter without a type and without contextual information may become an implicit any. The noImplicitAny compiler option reports this as an error.
function logValue(value) {
console.log(value);
}With noImplicitAny enabled, annotate the parameter:
function logValue(value: string | number): void {
console.log(value);
}A useful rule is:
- Let TypeScript infer local variables and straightforward return types.
- Annotate parameters when no context supplies their types.
- Annotate exported functions when the return type is part of the API contract.
- Add annotations when inference produces a type that is too broad or surprising.
| Location | Typical inference source | Example result | Column |
|---|---|---|---|
| Variable | Assigned value | `const total = 4` becomes `number` | |
| Return | Returned expressions | A function may return `string | number` |
| Callback parameter | Expected callback type | `map` supplies a `number` parameter | |
| Uncontextualized parameter | No source | `noImplicitAny` reports an error |
How inference flows
Inference is local but connected. The array type gives map its element type, map gives the callback its parameter type, and the callback's return value determines the result array type.
Exercise
What type does const labels = [1, 2, 3].map(n => n.toString()) have, and why?
Show answer
labels has type string[]. The array supplies number for n, toString() returns string, and map collects those results into a string array.