Skip to content
Nate
Stephens

Function Types

Callable types (aka Call signature)

Create a type alias (or interface) of a function (its param and return types):

You will almost always use the type alias approach

// TYPE ALIAS
type TwoNumberCalc = (x: number, y: number) => number;

const subtract: TwoNumberCalc = (x, y) => x - y;

// INTERFACE
interface TwoNumberCalculation {
  (x: number, y: number): number;
}

const add: TwoNumberCalculation = (a, b) => a + b;

void

void is a special type that's specifically used to describe a function return type.

The return value of a void function is intended to be IGNORED.

In JavaScript, a function that doesn't appear to return any value actually returns undefined.

A function returning undefined and a function's return type being set to void are not necessarily synonymous.

You can set any function's return type to void if you intend to ignore its return value.

function invokeInFourSeconds(callback: () => undefined) {
  setTimeout(callback, 4000);
}
function invokeInFiveSeconds(callback: () => void) {
  setTimeout(callback, 5000);
}

const values: number[] = [];
invokeInFourSeconds(() => values.push(4)); // <- ERROR
// Type 'number' is not assignable to type 'undefined'.
invokeInFiveSeconds(() => values.push(4));

Array.prototype.push returns a number, and our invokeInFourSeconds function above is unhappy about this being returned from the callback.


From the TypeScript Fundamentals, v3 course on FEM taught by Mike North.


Last Updated: