← TypeScript

Basic · 9 of 13 · 15 min read

Typing functions

Three ways to name a function type, what optional and default parameters really differ on, and why a void return accepts anything.

  • Functions

Parameters have to be annotated — there is nothing to infer them from. Return types usually do not. Beyond that, typing a function is about naming the signature so it can be reused, and knowing the three or four rules that are not obvious.

Three ways to name a signature

// 1. A type alias — the common one
type Add = (a: number, b: number) => number;

// 2. An interface with a call signature — when the function also has properties
interface Logger {
  (message: string): void;
  level: string;
}

// 3. Inline, for a one-off parameter
function run(fn: (name: string) => void) { fn("Ana"); }

const add: Add = (a, b) => a + b;   // parameters inferred from the alias
run((name) => console.log(name));
console.log(add(1, 2));              // 3

The alias form covers almost everything. The interface form is what you need when a function carries properties — a middleware with a .name, a mock with a .calls.

interface Logger {
  (message: string): void;
  level: string;
}

const log = ((message: string) => console.log(message)) as Logger;
log.level = "info";
log("hello");
console.log(log.level); // "info"

Note the contextual typing in const add: Add = (a, b) => a + b: the alias supplies the parameter types, so annotating them again is redundant.

Optional versus default

Both make the argument omittable at the call site. The difference is what the body has to handle.

function optional(name?: string) {
  return `Hi ${name?.toUpperCase() ?? "THERE"}`; // string | undefined inside
}

function defaulted(name = "there") {
  return `Hi ${name.toUpperCase()}`;             // string — the default already ran
}

console.log(optional(), defaulted());            // "Hi THERE" "Hi THERE"
console.log(optional("ana"), defaulted("ana"));
name?: string name = "there"
Omittable at the call yes yes
Type inside the body string | undefined string
Needs a check inside yes no
Appears in fn.length no no
Combining the two name?: string = "x" is an error —

An optional parameter may not precede a required one, which is a syntax rule rather than a style preference:

// function bad(a?: string, b: number) {} // A required parameter cannot follow an optional one
function fine(b: number, a?: string) { return [b, a]; }
console.log(fine(1));

There is also a third option worth knowing, for a public API: name: string | undefined forces the caller to pass something explicitly, so a forgotten argument is an error while a deliberate undefined is not.

Rest parameters

function sum(...values: number[]): number {
  return values.reduce((total, n) => total + n, 0);
}

console.log(sum(), sum(1, 2, 3)); // 0 6

const args: [number, number] = [1, 2];
console.log(sum(...args));         // 3

// Rest must be last, and it is implicitly optional:
// function bad(...a: number[], b: number) {}
// function alsoBad(...a?: number[]) {}

A rest parameter is always an array inside the function, so its annotation is the array type. It is the modern replacement for arguments, which arrow functions do not have at all.

Return types

Inferred by default, and worth annotating when you want the error to land in the right place:

function inferred(id: number) {
  return id.toString();     // inferred as string
}

function annotated(id: number): number {
  // return id.toString();  // Error reported HERE
  return id;
}

const a: number = annotated(1);
// const b: number = inferred(1); // the error lands at the call site instead

An async function always returns a promise, so the annotation wraps the value:

async function count(): Promise<number> {
  return 42;                     // not Promise.resolve(42) — both work
}

// async function wrong(): number { return 42; }
// The return type of an async function must be Promise<T>

count().then((n) => console.log(n)); // 42

void accepts anything

type Handler = () => void;

const handler: Handler = () => 42; // allowed
const result = handler();
console.log(result);                // undefined to the type system, 42 at runtime

Deliberate, and it is what makes an everyday line compile:

const target: number[] = [];
[1, 2].forEach((n) => target.push(n)); // push returns a number nobody wants
console.log(target);                    // [1, 2]

void means “the caller will not look at this”, not “nothing comes back”. Declaring void directly on a function is still checked:

// function f(): void { return 42; } // Type 'number' is not assignable to type 'void'
function f(): void { return; }       // fine
console.log(f());

Overloads

When the return type depends on the argument, a union cannot say so and overloads can:

function parse(value: string): string[];
function parse(value: number): number[];
function parse(value: string | number): string[] | number[] {
  return typeof value === "string" ? [value] : [value];
}

const a = parse("x"); // string[]
const b = parse(1);   // number[]
console.log(a[0]?.toUpperCase(), b[0]?.toFixed(1)); // "X" "1.0"

The implementation signature is not callable from outside — it only has to be compatible with every overload above it. Before reaching for overloads, check whether a generic says it more simply; overloads are the tool when the shape of the return changes, not just its type parameter.

this in a function

class Counter {
  count = 0;

  startBroken() {
    setInterval(function () {
      // this.count += 1; // 'this' implicitly has type 'any' under noImplicitThis
    }, 1000);
  }

  start() {
    setInterval(() => {
      this.count += 1; // the arrow keeps the surrounding `this`
    }, 1000);
  }

  // An explicit `this` parameter, erased at compile time:
  describe(this: Counter) { return this.count; }
}

console.log(new Counter().describe()); // 0

The this parameter is a TypeScript-only declaration that disappears from the emit — it is not an argument, and it does not shift the positions of the real ones.

Parameter counts are checked loosely

A function may ignore trailing parameters it was offered, which is what makes callbacks pleasant:

type Handler = (value: string, index: number) => void;

const ignoresIndex: Handler = (value) => console.log(value); // fine
// const wantsMore: Handler = (v, i, extra: boolean) => {};  // rejected

["a", "b"].forEach((value) => console.log(value)); // the everyday case
ignoresIndex("a", 0);

Fewer is fine; more is not, because the extra argument would be undefined.

Common mistakes

Annotating name?: string = "x"

Mistake. Combining the optional marker with a default. Why it fails. It is a syntax error — the default already makes the parameter omittable. What to do instead. Pick one. A default if there is a sensible fallback, ? if absence is meaningful.

Expecting a void return to mean “returns nothing”

Mistake. Being surprised that () => 42 satisfies () => void. Why it fails. The rule is about the caller ignoring the result, and it exists so callbacks like arr.push can be passed directly. What to do instead. Nothing, usually. If a function genuinely must return nothing, annotate it : void at the declaration, where it is checked.

Reaching for overloads where a generic would do

Mistake. Three overloads that differ only in one type. Why it fails. More signatures to maintain, and the implementation signature has to satisfy all of them with a widened union. What to do instead. function identity<T>(value: T): T — one signature, every type.

Check yourself

4 questions from the bank on what you just read. Answering here does not affect your quiz history.

What is the difference between an optional parameter and one with a default?

What are the three ways to give a function a named type?

A void return type says the caller must not use the result, which is weaker than saying nothing is returned.

Why is this assignment allowed?

Code sample
type Handler = () => void;

const handler: Handler = () => 42;

What does a function overload let you express that a union parameter cannot?

Practise Functions →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.