Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 96 ยท Functions

Typing Functions

Learn to type TypeScript functions - parameter and return types, optional and default parameters, rest parameters, arrow functions, void and never return types.

Functions are where types pay off the most. A function's parameters and return value form a contract: callers must pass the right arguments, and the body must hand back what it promises. Once that contract is written down, TypeScript checks every call site in your project, and your editor can show the signature as you type.

This lesson covers everything you need to type ordinary functions: parameter and return annotations, optional and default parameters, rest parameters, arrow functions, and the two special return types void and never. If you need a refresher on how functions work in plain JavaScript, see Functions, Parameters and Arrow Functions in the JavaScript tutorial.

Parameter and return types

Annotate each parameter after its name, and the return type after the parameter list:

TypeScript Parameters and a return 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.

Parameters must be annotated (or contextually typed, as you'll see below). Under strict, noImplicitAny reports a parameter without a type as error TS7006, "Parameter 'x' implicitly has an 'any' type." The return type is optional: TypeScript infers it from the return statements, and add returns number here.

Should you write return types?

Inference is accurate, so you can skip return types in small, private helpers. Writing them is worth it for exported and public functions:

  • The annotation documents intent, and the body is checked against it. If you accidentally return undefined on one path, the error appears inside the function, not at a distant call site.
  • It stops implementation details from leaking. Without an annotation, a refactor inside the body can silently change the public type.
  • Large projects type-check a bit faster, because the checker doesn't have to infer the type before it can check callers.

TypeScript checks the call

Every call is checked for the number and the types of its arguments. This example fails on purpose, so you'll only see the errors:

TypeScript Wrong arguments (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.

You get one error per bad call:

TEXT
main.ts(5,1): error TS2554: Expected 2 arguments, but got 1.
main.ts(6,13): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
main.ts(7,24): error TS2554: Expected 2 arguments, but got 3.

Plain JavaScript would have run all three calls, filling the missing argument with undefined and ignoring the extra one. TypeScript treats the parameter list as exact: every parameter is required unless you say otherwise.

Optional and default parameters

Add ? after a parameter name to make it optional. Inside the function its type includes undefined, so you must handle the missing case. A default value makes a parameter optional too, and TypeScript infers the type from the default:

TypeScript Optional and default parameters

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 rules to remember:

  • An optional parameter (title?: string) can't come before a required one. function f(a?: string, b: string) is error TS1016, "A required parameter cannot follow an optional parameter."
  • A default parameter can appear anywhere, but if it's before a required one, callers must pass undefined explicitly to use the default. Keep defaults at the end.
  • Don't combine both: step?: number = 1 is error TS1015, "Parameter cannot have question mark and initializer." A default already makes the parameter optional for callers, and inside the body its type is the plain number, never undefined.

Prefer a default value to an optional parameter whenever a sensible default exists. The body gets a simpler type (number instead of number | undefined), and readers see the default right in the signature.

Rest parameters

A rest parameter (...name) collects any number of remaining arguments into an array. Its type must be an array or a tuple type:

TypeScript Rest parameters and spreading

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.

sum(...prices) works because sum accepts any number of numbers. Spreading into fixed parameters is stricter: point(...coords) compiles only because coords is a tuple of exactly two numbers. If coords were a plain number[], TypeScript would report error TS2556, "A spread argument must either have a tuple type or be passed to a rest parameter," since an array could hold any number of elements. Arrays and Tuples shows more tuple tricks, including rest elements like [string, ...number[]].

Arrow functions and function expressions

Arrow functions and function expressions use the same annotations. The return type goes after the parameter list, before the arrow:

TypeScript Arrow 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.

The callbacks passed to filter and map have no annotations at all. TypeScript knows that numbers.filter expects a function receiving a number, so it types n from that context. This contextual typing is why most callbacks in TypeScript code look exactly like plain JavaScript. The next lesson, Function Types and Callbacks, explains how to write such function types for your own APIs.

makeUser has an inferred return type of { name: string; age: number; isAdult: boolean }. The last example also shows that an async function always returns a Promise: its annotation is Promise<number>, not number. Promises and async/await covers async typing in detail. (Top-level await works in our editor because each example runs as an ES module.)

The void return type

A function that doesn't return a useful value has the return type void. It's inferred automatically when a function has no return statement or only bare return; statements:

TypeScript
function log(message: string): void {
  console.log(`[log] ${message}`);
}

For a function declaration that says : void, returning a value is an error, because the annotation promises nothing useful comes back.

void-returning callbacks

Function types with a void return are more relaxed, and on purpose. When a parameter's type is (item: T) => void, you're allowed to pass a function that returns something; the caller simply promises to ignore the result:

TypeScript Callbacks that return void

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.

Without this rule, the extremely common (x) => list.push(x) callback would be an error, because push returns a number. Notice the last lines, though: calling onEvent() really returns 42 at runtime, yet its static type is void, so TypeScript won't let you use it as a number. void means "don't rely on this value," which is different from undefined. any, unknown, never and void compares the two in depth.

The <T> in forEachItem<T> makes the function generic, so it works for arrays of any element type. Generics get their own lesson in Generics; here you only need to know that T stands for "whatever the array contains."

Functions that never return: never

A function that always throws, or loops forever, never finishes normally. Its return type is never:

TypeScript never for functions that always throw

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.

Because fail returns never, TypeScript knows execution can't continue after the call. This matters for control-flow analysis: a never call can end a branch just like throw or return. One detail: a function expression or arrow that always throws is inferred as never, but a function declaration like fail is inferred as void, so write : never explicitly to get the effect. The (error as Error) assertion is there because caught values have type unknown in strict mode; Error Handling shows safer ways to narrow them.

Function declarations and hoisting

Types don't change JavaScript's rules about where functions can be used. Function declarations are hoisted, so you can call them before the line that defines them. const arrow functions aren't: calling one before its definition throws a ReferenceError at runtime. TypeScript reports the obvious cases ("Block-scoped variable 'x' used before its declaration," TS2448), but it can't catch every one, for example when the call happens inside another function that runs too early.

A common style is to use function declarations for top-level, named functions (they read well and hoist) and arrow functions for callbacks and short helpers. Both are typed the same way.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given function area(w: number, h = w): number { return w * h; }, what does area(3) return?

    A default can refer to earlier parameters. h defaults to w, so the result is 3 * 3 = 9, and h is inferred as number.
  2. 2. Does function greet(title?: string, name: string) {} compile?

    Error TS1016. Optional parameters must come after all required ones. Reorder the parameters or use a default value with an explicit undefined at call sites.
  3. 3. With function point(x: number, y: number) and const values = [1, 2]; (inferred as number[]), what happens with point(...values)?

    Spreading into fixed parameters requires a tuple type. Annotate values as [number, number] or use as const to make it a tuple.
  4. 4. A parameter is typed callback: (n: number) => void. Can you pass (n) => list.push(n), which returns a number?

    Function types with a void return accept functions that return anything. The caller promises not to use the result.
  5. 5. What is the best return type for a function whose body always ends with a throw statement?

    never means the function never completes normally. Calls to it end a branch for control-flow analysis, just like throw.

Summary

  • Annotate parameters as name: Type and the return type after the parentheses: function f(a: number): string. Return types are inferred, but annotate exported functions.
  • Calls are checked for argument count and types (TS2554, TS2345).
  • param?: T makes a parameter optional with type T | undefined; a default value (param = 1) makes it optional with type T. Required parameters can't follow optional ones.
  • Rest parameters (...items: T[]) collect extra arguments; spreading into fixed parameters needs a tuple.
  • Arrow functions use the same annotations; callbacks are usually typed contextually, with no annotations needed.
  • void means "no useful value"; void-returning function types accept functions that return something. never marks functions that always throw.

Next: Function Types and Callbacks