typestar

Function types and overloads in TypeScript

A call signature as a type, optional and default parameters, overloads.

type Formatter = (value: number, digits?: number) => string;

const fixed: Formatter = (value, digits = 1) => value.toFixed(digits);

function first(values: string[]): string | undefined;
function first(values: string[], fallback: string): string;
function first(values: string[], fallback?: string): string | undefined {
  return values[0] ?? fallback;
}

type Handler = {
  (event: string): void;
  readonly type: "handler";
};

const handler = ((event: string) => console.log(event)) as Handler;

console.log(fixed(2.345, 2), first([], "none"), first(["a"]));
console.log(typeof handler);

How it works

  1. A function type can be written inline or named.
  2. Overload signatures narrow the return type per argument shape.
  3. The implementation signature is not callable from outside.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
585
Tokens
166
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 105 seconds.

Type this snippet

Step 2 of 5 in Functions & tuples, step 17 of 23 in Types & annotations.

← Previous Next →