Sub topic 3
How TypeScript Infers Type Arguments
TypeScript can often choose the type arguments for a generic function from the values you pass to it. This process is called type argument inference. You should already know basic TypeScript types, interfaces, type aliases, functions, unions, and classes.
Inference reduces repetition while preserving precise types. If a function receives a number, TypeScript can infer its type parameter as number. If the function connects two values, inference can also check whether those values have compatible types.
Inferring from Function Arguments
Consider a generic function that returns its argument:
function identity<T>(value: T): T {
return value;
}
const message = identity("hello");
const count = identity(42);
console.log(message.toUpperCase()); // string
console.log(count.toFixed(2)); // numberFor identity("hello"), TypeScript infers T as string. For identity(42), it infers T as number. The return type is linked to the argument type.
You can supply a type argument explicitly when you want to make the choice visible or force a particular type:
const text = identity<string>("hello");
const value = identity<number>(42);
console.log(text, value);Explicit type arguments use angle brackets after the function name. They are useful when inference does not express your intent clearly, but inference is usually the simpler choice.
Inference from Collections
TypeScript also infers a type parameter from an array:
function firstElement<T>(items: T[]): T | undefined {
return items[0];
}
const firstNumber = firstElement([10, 20, 30]);
const firstWord = firstElement(["red", "blue"]);
console.log(firstNumber); // number | undefined
console.log(firstWord); // string | undefinedThe array [10, 20, 30] gives T the type number. Because an array can be empty, the return type includes undefined.
When an array contains different types, TypeScript infers a union:
function lastElement<T>(items: T[]): T | undefined {
return items[items.length - 1];
}
const result = lastElement([1, "two"]);
console.log(result); // string | number | undefinedThe inferred T is string | number.
Context Can Affect Inference
Inference does not always come only from the arguments. The expected type can also provide context:
function createPair<T>(value: T): [T, T] {
return [value, value];
}
const pair: [string, string] = createPair("ready");
console.log(pair);The argument already suggests T is string, and the variable annotation agrees with that result. If the argument and expected type conflict, TypeScript reports an error instead of silently changing the type.
When to Write Type Arguments Explicitly
Use inference when the result is clear:
const numbers = firstElement([1, 2, 3]);Supply a type argument when you need a wider or more specific type:
function makeList<T>(item: T): T[] {
return [item];
}
const values = makeList<string | number>(42);
values.push("answer");
console.log(values);Without the explicit type argument, T would usually be inferred as number, so adding a string later would fail. The explicit union tells TypeScript that both types are intended.
| Situation | Typical choice |
|---|---|
| The argument clearly determines the type | Use inference |
| The desired type is wider than the argument | Supply a type argument |
| Inference produces an unclear or unwanted type | Supply a type argument |
| The call should document an important API decision | Consider a type argument |
Common Inference Mistakes
A type parameter should connect meaningful parts of an API. This function has a type parameter, but it provides no useful relationship:
function logValue<T>(value: T): void {
console.log(value);
}T appears only once, so unknown is clearer:
function logValue(value: unknown): void {
console.log(value);
}
logValue("status");
logValue(404);Also remember that explicit type arguments can be incorrect if they claim a type the value does not have:
function wrap<T>(value: T): T[] {
return [value];
}
// const bad = wrap<string>(42); // Error
const good = wrap<string>("ok");
console.log(good);Exercise
What type does TypeScript infer for firstElement(["a", "b"]), whose return type is T | undefined?
Show answer
It infers T as string, so the complete result type is string | undefined.