Function Inference

TS Often Knows the Function Type From Context

Function Inference

TypeScript uses the context — where a function is assigned or passed — to infer its types. Less annotation, same safety.

3 min read Level 1/5 #typescript#inference#contextual
What you'll learn
  • Recognize contextual function typing
  • Use it to avoid redundant annotations

When a function is assigned to or passed to something with a known type, TS infers the function’s parameter types from context. You don’t have to repeat them.

Variable Assignment

type Handler = (event: string) => void;

const onClick: Handler = e => {
  // e is inferred as string
  console.log(e.toUpperCase());
};

The annotation on the variable tells TS the function’s shape. Inside the function, e is typed automatically.

Callback Arguments

const nums = [1, 2, 3];

nums.map(n => n * 2);
//       ^ n: number (inferred from Array<number>'s map)

The callback’s parameter is inferred from the array element type.

Multiple Parameters

[1, 2, 3].reduce((sum, n) => sum + n, 0);
//                ^ sum: number, n: number (from Array<number>.reduce<number>)

Function Returns

If you return a function from another function, the inner function’s signature can also be inferred from context:

function makeAdder(x: number): (y: number) => number {
  return y => x + y;
  //     ^ y inferred as number from the return type
}

When Inference Falls Short

Inference works when the context is known. For top-level declarations with no context, you’d need annotations:

const fn = (x) => x + 1;
//          ~  Parameter 'x' implicitly has an 'any' type.

const fn = (x: number) => x + 1;   // ✓

The standalone variable declaration has no context, so x defaults to any (or errors with noImplicitAny).

Up Next

What void actually means in a function context.

`void` Return →