Sub topic 2
What the compiler infers for you
This chapter assumes you can already annotate function parameters and return types, as the previous chapter showed. You should also know TypeScript's primitive, object and union types, and you should be able to hover over a symbol in your editor or run tsc to see the types it reports. The examples assume "strict": true in tsconfig.json, which turns on noImplicitAny and strictNullChecks.
Where inference works and where it doesn't
TypeScript infers some parts of a function signature and requires you to write others.
| Part of the function | Inferred? | Notes |
|---|---|---|
| Return type | Yes | Computed from the `return` statements in the body. |
| Parameter type | Only in two cases | From a default value, or from context when the function is passed where a function type is expected. |
| Parameter type with no default and no context | No | Error under `noImplicitAny`. |
| Type arguments of a generic call | Yes | Covered in the chapter on generic functions. |
Parameters are the boundary of a function, so TypeScript expects you to state them. The body is checked against what you wrote. The return type is a consequence of the body, so the compiler can work it out.
Return types come from the body
The compiler collects the type of every return expression and combines them into a union.
function parse(input: string) {
if (input.trim() === "") {
return null;
}
return Number(input);
}
const result = parse("42"); // number | nullHovering over parse shows (input: string) => number | null. Because null is in the union, every caller must handle it before using the number.
A function with a code path that never returns a value gets undefined in its union:
function double(n: number) {
if (n > 0) {
return n * 2;
}
}
const d = double(3); // number | undefinedThis is legal by default. Enable noImplicitReturns to make the compiler report "Not all code paths return a value" instead.
Inference also works through await. An async function with no annotation is inferred as returning a Promise of whatever its return expressions produce.
async function loadCount() {
return 1;
}
// loadCount: () => Promise<number>Literal types and widening
Inference is not always as narrow as it could be. A single literal return is widened to its general type, while a union of several literals is kept.
function label() {
return "ready";
}
// label(): string
function sign(n: number) {
return n >= 0 ? "positive" : "negative";
}
// sign(n): "positive" | "negative"The same widening applies to properties of returned objects. Object properties are mutable by default, so the compiler assumes they may change and widens them:
function makePoint() {
return { kind: "point", x: 1 };
}
// { kind: string; x: number }
function makeFixedPoint() {
return { kind: "point", x: 1 } as const;
}
// { readonly kind: "point"; readonly x: 1 }This matters when the object feeds a discriminated union. A kind widened to string no longer matches "point". Use as const, or annotate the return type, to keep the literal.
Parameter types from defaults
A default value gives the compiler enough information to type the parameter, and it also makes the parameter optional.
function pad(text: string, width = 10, fill = " ") {
return text.padEnd(width, fill);
}
pad("hi"); // ok
pad("hi", 5, "-"); // ok
// pad("hi", "5"); // error: Argument of type 'string' is not assignable to parameter of type 'number'Here width is number and fill is string. A default of 0 gives number, not the literal 0, because the compiler widens it.
If the default is not representative, annotate the parameter. A default of null or [] says little about the intended type:
function collect(items: string[] = []) {
return items.length;
}Void and never
Inference separates two cases that look alike. A function with no return value is inferred as void. A function expression or arrow function that can never complete is inferred as never.
function logIt(message: string) {
console.log(message);
}
// logIt: (message: string) => void
const fail = (message: string) => {
throw new Error(message);
};
// fail: (message: string) => neverA function declaration that always throws is inferred as void, not never. Declarations are hoisted, so the compiler cannot treat them as non-returning when it analyzes the code that calls them. If you want never from a declaration, write it:
function fail2(message: string): never {
throw new Error(message);
}Only an explicitly annotated never lets control-flow analysis treat the code after a call as unreachable.
When inference fails: recursion
When a function calls itself inside a return expression, the compiler cannot finish computing the return type, because it is part of its own definition.
function factorial(n: number) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
// error: 'factorial' implicitly has return type 'any' because it does not
// have a return type annotation and is referenced directly or indirectly
// in one of its return expressions.Annotating the return type fixes it:
function factorial(n: number): number {
return n <= 1 ? 1 : n * factorial(n - 1);
}The same error appears with mutually recursive functions. Annotating one of them is enough to break the cycle.
An annotation changes what is checked
Without an annotation, the body defines the contract. With an annotation, the contract defines what the body may do. Compare these two versions:
type User = { id: number; name: string };
function findName(users: User[], id: number) {
const user = users.find(u => u.id === id);
return user;
}
// returns User | undefined, even though the name suggests a string
function findNameChecked(users: User[], id: number): string | undefined {
const user = users.find(u => u.id === id);
// return user; // error: Type 'User | undefined' is not assignable to type 'string | undefined'
return user?.name;
}The first version compiles because the compiler accepts whatever you return, including a mistake. The second states the intent, so the compiler reports the mistake at the return line, where it was made.
An annotation also gives the return expression a contextual type. An empty array literal in an unannotated return is inferred as never[] under strictNullChecks, which is rarely what you want.
function noItems() {
return [];
}
// never[]
function noNames(): string[] {
return [];
}
// string[]Deciding when to annotate
Use these criteria to choose between relying on inference and writing the return type.
- Annotate exported functions, library entry points and methods on public classes. The type is a contract, and the annotation keeps it stable when the body changes.
- Annotate recursive functions, and the implementation signature of overloads, which the later chapter on overloads covers.
- Annotate when you want literal types preserved, such as
"ok" | "error", or when the body returns[],{}ornullplaceholders. - Annotate when the function is long and you want readers to see the result type without reading the body.
- Rely on inference for small local helpers, callbacks passed to
maporfilter, and one-expression arrows whose result is obvious.
Some projects enable the isolatedDeclarations compiler option, which requires explicit annotations on exported functions so that declaration files can be generated without type-checking the whole program. If your team uses it, the compiler enforces the first rule for you.
Common errors
- Implicit
anyparameter.function f(x) {}fails undernoImplicitAny. Annotate the parameter, or give it a default value. - Widened literals. A returned object's
kind: "point"becomesstring. Useas constor an annotation. - Unexpected
| undefined. A branch that falls through without returning addsundefinedto the inferred type. Add a finalreturn, or turn onnoImplicitReturns. voidfrom a throwing declaration. A declaration that only throws is inferred asvoid. Annotate: neverwhen you need it.- Circular return inference. A recursive call inside a
returnexpression requires an annotation.
Exercise
What return type does the compiler infer for this function, and what one change makes callers see "low" | "high" instead of a wider type? function level(n: number) { if (n > 10) { return "high"; } return "low"; }
Show answer
The two returns produce the union "high" | "low", which is not a single literal, so it is kept as is and callers already see "low" | "high". A single return "high" alone would widen to string, so the answer is that no change is needed here. Adding an explicit : "low" | "high" annotation would only lock the contract in, so a later edit such as return "medium" becomes an error inside the function.
Exercise
Why does function sum(n: number) { return n === 0 ? 0 : n + sum(n - 1); } fail to compile under strict, and how do you fix it?
Show answer
The return type depends on a call to sum inside its own return expression, so the compiler cannot determine it and reports an implicit any return type. Annotate the return type: function sum(n: number): number { ... }.