Skip to content
jshacks.dev
TypeScript

Generic Inference From Return Types

How TypeScript infers a generic type argument from the type you expect back, why it ranks below arguments, and when to use NoInfer or explicit type arguments.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the TypeScript, Node.js and JavaScript logos.

Most generic inference runs from arguments to type parameters: you pass a string, and T becomes string. TypeScript also infers in the other direction. When a call appears where a particular type is expected, the compiler uses the expected type as evidence about the type parameters, even though nothing in the argument list mentions them. This is why const names: Set<string> = new Set() works with no <string> written anywhere, and why a function whose generic appears only in its return type behaves differently depending on where you call it. This post explains how return-type inference works, how it ranks against argument inference, what happens when there is no evidence at all, and the tools for steering it. It describes TypeScript 6.x, and the native compiler preview that TypeScript 7 is built on infers the same way. The reference is the handbook chapter on generics and the TypeScript 5.4 release notes for NoInfer.

Inference with no argument evidence

Start with a function whose type parameter appears only in the return type.

empty.tsTypeScript
function make<T>(): T[] {
  return [];
}

const a = make();
const first: string = a[0];
Text
empty.ts(6,7): error TS2322: Type 'unknown' is not assignable to type 'string'.

There are no arguments and no expected type, so the compiler has no candidates for T. It falls back to the constraint, which here is the implicit unknown, and a is unknown[]. The error appears on the use, not the call, which is a common pattern: a generic function that cannot infer silently produces a useless type and the complaint shows up later.

Now give the call an expected type.

empty.tsTypeScript
function make<T>(): T[] {
  return [];
}

const a: string[] = make();
const first: string = a[0];
console.log(a.length);
Text
0

The declared type of a supplies the evidence. The compiler sees a call returning T[] in a position that expects string[], matches the two, and infers T as string. The program prints 0 at run time, and compiles with no errors. This is return type inference, sometimes called contextual return type inference, since the context of the call position is the source of information.

How the compiler ranks the evidence

A call can have several sources of candidates for one type parameter: the arguments, the expected return type, and defaults. They are not equal. Candidates from arguments have the highest priority. Candidates from the expected return type are used when there is nothing better, and also to give contextual types to function-expression arguments, but an argument candidate overrides them.

priority.tsTypeScript
function wrap<T>(value: T): T[] {
  return [value];
}

const ok: (string | number)[] = wrap(1);
const bad: number[] = wrap("a");
Text
priority.ts(6,7): error TS2322: Type 'string[]' is not assignable to type 'number[]'.
  Type 'string' is not assignable to type 'number'.

In the first call the argument gives number, which wins over the expected string | number, and number[] is assignable to the wider array, so it compiles. In the second, the argument "a" gives string, which wins over the expected number, so the result is string[], and the mismatch is reported against the declaration. The expected type did not rescue the call or change T, since the argument had priority.

This ordering is sensible. The argument is a value that actually exists, and the expected type is only a hope about how the result will be used. If the two disagree, the value is right and the use is wrong.

Where it shows up in everyday code

Constructors of generic classes are the most frequent case. A class such as Set<T> or Promise<T> has a type parameter that is not always visible in its arguments, and the declared type of the variable fills it in.

promise.tsTypeScript
const p: Promise<number> = new Promise(resolve => {
  resolve(1);
});

p.then(n => console.log(n + 1));
Text
2

The new Promise call has no type argument, and its executor callback does not mention a type. The expected type Promise<number> provides T = number, so resolve is typed to take a number. The same mechanism types the parameters of callbacks passed to a generic function when the function's own return is assigned to a typed target.

Your own factories behave the same way.

factory.tsTypeScript
interface Box<T> {
  value: T | undefined;
}

function emptyBox<T>(): Box<T> {
  return { value: undefined };
}

const nums: Box<number> = emptyBox();
nums.value = 3;
nums.value = "three";
Text
factory.ts(11,1): error TS2322: Type 'string' is not assignable to type 'number | undefined'.

The call to emptyBox infers T from the declaration of nums, so the later assignment of a string is caught. Without the annotation, emptyBox() would produce Box<unknown>, and every assignment would be accepted.

Return-only generics are a smell

A function whose type parameter appears only in its return type is a promise the function cannot keep. The compiler will let the caller choose any T, and nothing in the function checks that the result really is one.

unsafe.tsTypeScript
function parse<T>(text: string): T {
  return JSON.parse(text);
}

const user = parse<{ name: string }>("42");
console.log(user.name);
Text
undefined

The call compiles, and the program prints undefined at run time, because the text is the number 42, not an object with a name. The type parameter is a cast in disguise. It does no harm when the caller is careful, but it spreads a trust assumption through the code without any visible assertion. If you must write such a function, say what it is in its name or doc comment, or have it accept a validator argument so that T appears in the input as well, and the compiler can check the connection.

The JSON.parse return type of any makes this compile without a cast inside the function. Returning unknown from the function and validating in the caller is the safer shape.

Blocking inference with NoInfer

Sometimes a position should be checked against T and not contribute to it. TypeScript 5.4 added the NoInfer utility type for this. Wrapping a type in NoInfer tells the compiler not to use that position as a source of candidates.

noinfer.tsTypeScript
function pick<T extends string>(items: T[], fallback: NoInfer<T>): T {
  return items.includes(fallback) ? fallback : items[0];
}

const a = pick(["red", "green"], "red");
const b = pick(["red", "green"], "blue");
Text
noinfer.ts(6,34): error TS2345: Argument of type '"blue"' is not assignable to parameter of type '"red" | "green"'.

Without NoInfer, the second argument would also contribute a candidate, "blue", and T would become "red" | "green" | "blue", so the bad call would compile. With it, only the first argument decides T, and the fallback is checked against the result. This is the clean way to say "infer from here, validate here". The same tool applies to return positions, to stop an expected type from steering inference where you do not want it to.

Explicit type arguments

If inference gives the wrong answer or no answer, you can always write the type argument. make<string>() says it outright. Use it when the call is not in a position with a useful expected type, for instance as an argument to another generic function, where the contextual type may be another unresolved parameter. Writing the type argument is also the clearest signal to a reader when the function has a return-only generic.

Partial inference is not supported. If you give some type arguments explicitly, the compiler does not infer the others, and defaults fill the rest. For a function with two type parameters where you want to fix one and infer the other, the usual workaround is to split it into a curried pair, or to use a default and a helper type.

Return-type context in callbacks

The expected type also flows into function expressions that you pass as arguments. In array.map(x => ...), the parameter x is typed from the array, and the result of the callback determines U. When the result of map is itself assigned to a typed target, the compiler can use that target as a hint for U while checking the callback body, which is how const names: string[] = users.map(u => u.name) can give the callback return a contextual type. The hint is weak. If the callback returns something else, U is inferred from the actual return, and the mismatch is reported on the declaration.

Practical guidance

Annotate the variable at the call site when a factory has a return-only type parameter, and the type is a documented result. Prefer designs where T appears in an argument, because then inference does not depend on the caller's annotation. Use NoInfer for parameters that should be checked and not used as evidence, such as defaults and fallbacks. When an error mentions unknown in a place you did not write it, look for a generic call that had no evidence.

Common mistakes

The first is assuming an annotation will override argument inference, when it is the lower-priority source. The second is writing a return-only generic that parses or fetches data, which turns the type parameter into an unchecked assertion. The third is expecting partial explicit type arguments to infer the rest. The fourth is adding NoInfer around a position that is the only evidence for T, which leaves the compiler with nothing and yields unknown.

When this does not apply

Return-type inference needs a typed target. Chained calls, const x = make() with no annotation, and arguments to untyped functions provide no expected type, so the fallback applies. Inference also stops at a function boundary: the type of a variable inside the callee is not available to the caller. For public APIs, write explicit signatures and do not rely on callers' annotations.

Share

Keep reading

Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read
Flat illustration of an editor window full of code, with the TypeScript, Node.js, npm, Vite and JavaScript logos.
TypeScript

What Is TypeScript, and Why Use It?

TypeScript adds static types to JavaScript and checks them before your code runs. Learn what it is, what it catches, what it costs and when to use it.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.