Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 96 ยท Functions

Function Types and Callbacks

Learn TypeScript function types - arrow-style type expressions, call signatures, typing callbacks and higher-order functions, contextual typing and function assignability.

In JavaScript, functions are values. You store them in variables, pass them as arguments, return them from other functions and keep them in objects. To type any of that, you need a way to write down the type of a function itself: which parameters it takes and what it returns.

This lesson shows the two ways to write function types (type expressions and call signatures), how to type callbacks and higher-order functions, how contextual typing lets callbacks skip annotations, and the rules TypeScript uses to decide whether one function can stand in for another. That last part explains a few results that surprise newcomers, such as why passing a one-parameter function where two parameters are expected is perfectly fine.

Function type expressions

A function type expression looks like an arrow function without a body:

TypeScript
(a: number, b: number) => number

Read it as "a function that takes two numbers and returns a number." You can use it anywhere a type goes, but it's usually given a name with a type alias:

TypeScript Naming a function type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The arrow functions on the right have no annotations. Because each variable is declared as BinaryOp, TypeScript knows a and b are numbers and checks that the body returns a number. This is contextual typing: the type flows from the declaration into the function, the same way it flows into callbacks passed to map or filter (see Type Inference).

The parameter names in a function type are only documentation. (base, exponent) => ... fits BinaryOp even though the type calls them a and b. Only the positions and types matter.

The names are not optional, though. In type Handler = (string) => void, TypeScript reads string as a parameter name with no type, so under strict you get error TS7051, "Parameter has a name but no type. Did you mean 'arg0: string'?" Always write (value: string) => void.

Typing callbacks

A function that takes another function as an argument is called a higher-order function. You type the callback parameter with a function type, and callers get full checking and inference for free:

TypeScript Higher-order functions with typed callbacks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

None of the arrow functions passed in needs a single annotation: score, index, i, attempt and error all get their types from the parameter they're passed to. retry is generic (<T>), so the type of result is inferred from what the task returns, here string. You'll learn to write generic functions in Generics.

Two conventions appear here. An underscore (_) names a parameter you don't use, which makes positional callbacks like (_, index) => ... readable. And the error callback receives unknown, not Error, because anything can be thrown in JavaScript; Error Handling explains how to narrow it properly.

Functions that return functions

The return type can be a function type too. This is how you type factories and closures:

TypeScript Returning functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Arrows in types read right to left: (a: number) => (b: number) => number is "a function taking a that returns (a function taking b that returns a number)." The JavaScript side of closures is covered in Closures.

Call signatures

A function type expression can't describe a function that also has properties. JavaScript functions are objects, so they can carry extra data, and some libraries rely on that. For those, write a call signature inside an object type: the parameter list followed by : and the return type (a colon, not an arrow):

TypeScript A call signature with properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Validator values can be called like functions (minThree('abcd')) and read like objects (minEight.rule). Object.assign attaches the property and returns a value whose type is the function type intersected with { rule: string }, which matches Validator. An object type can hold several call signatures, which is one way to describe overloads.

There are also construct signatures, written with new, which describe things you call with new:

TypeScript
interface PointConstructor {
  new (x: number, y: number): { x: number; y: number };
}

You'll use the shorthand new (...args) => T when you pass classes around in Classes, Interfaces and Structural Typing.

Which syntax to use?

Syntax Example Use for
Function type expression type Fn = (x: number) => string Almost all function types
Call signature interface Fn { (x: number): string; id: string } Functions with properties, overload sets
Method in an interface interface Api { load(id: string): void } Functions that belong to an object

Avoid the built-in Function type. It accepts any function and returns any when called, so it switches off almost all checking. Write the actual signature instead, or (...args: never[]) => unknown if you truly accept any function.

When is one function assignable to another?

Callbacks are only useful if you can pass functions with slightly different shapes. TypeScript compares function types by their parameters and return types, using rules that match how JavaScript calls work.

Fewer parameters are fine

A function with fewer parameters can be used where more are expected. JavaScript ignores extra arguments, so a callback that doesn't need them is safe:

TypeScript Fewer parameters are allowed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Array.prototype.map passes three arguments (value, index, array), yet nobody writes all three. If TypeScript required the full parameter list, almost every callback in existence would be an error.

More required parameters are not

The opposite is unsafe: if a callback requires a parameter that the caller never passes, it would receive undefined. This example fails on purpose:

TypeScript A callback that needs too much (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript reports:

TEXT
main.ts(6,9): error TS2345: Argument of type '(x: number, y: number) => void' is not assignable to parameter of type '(x: number) => void'.
  Target signature provides too few arguments. Expected 2 or more, but got 1.

Making y optional (y?: number) or giving it a default fixes it, because then the function can genuinely be called with one argument.

Parameter and return types

The other two rules are about the types themselves:

  • Return types are covariant. A function returning a more specific type can stand in for one returning a wider type: () => 'yes' works where () => string is expected. (A void return is the special case from Typing Functions: it accepts any return type.)
  • Parameter types are contravariant under strictFunctionTypes. A function that accepts a wider type can stand in for one with a narrower parameter: (value: string | number) => void works where (value: string) => void is expected, because it can handle every string. The reverse is rejected, since a function that only handles strings might be given a number.

Method-style members (handle(x: string): void in an interface) are checked more loosely, "bivariantly," for compatibility with older code. Type Compatibility and Variance explains covariance and contravariance properly, with arrays and event handlers as examples.

When you design a callback type, don't mark its parameters optional just because some callbacks won't use them. Because shorter callbacks are always accepted, (value: string, index: number) => void already allows (value) => .... An optional index?: number would instead force every callback that does use index to handle undefined.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is wrong with type OnChange = (string) => void?

    In a function type, each parameter needs a name. (string) => void declares a parameter called string. Write (value: string) => void instead.
  2. 2. Can (n: number) => console.log(n) be passed where (n: number, index: number, all: number[]) => void is expected?

    Leaving out trailing parameters is always safe, since JavaScript ignores extra arguments. That is why short array callbacks compile.
  3. 3. Which type describes a function that can be called with a string AND has a numeric version property?

    A call signature inside an object type describes something callable that also has properties. The method version describes an object with a call method, not a callable value.
  4. 4. Under strictFunctionTypes, which function can be assigned to type Handler = (value: string) => void?

    Parameters are contravariant. A function that accepts string or number can handle every string. The literal union version could not handle arbitrary strings, and the two-parameter version requires an argument the caller never passes.

Summary

  • A function type expression like (a: number, b: number) => number describes a function's parameters and return type. Parameter names are required but don't have to match.
  • Declaring a variable or parameter with a function type gives the function contextual typing: its parameters need no annotations.
  • Callback parameters, factories and curried functions are all typed with function types; arrows in types read right to left.
  • Call signatures ({ (x: string): boolean; rule: string }) describe callable values with properties; construct signatures add new.
  • Avoid Function; write real signatures.
  • Assignability: fewer parameters are fine, extra required parameters are not; return types are covariant, parameter types contravariant (methods are bivariant).

Next: Function Overloads