Dev Helpers
← Back

Overload input and output types

Overload input and output types using TypeScript.

Open this example in the interactive library

Source code

type Task = (name: string, attempt?: number) => string;
const task: Task = (name, attempt = 1) => name + " #" + attempt;
console.log(
  (() => {
    function length(v: string): number;
    function length(v: string[]): number;
    function length(v: string | string[]) {
      return v.length;
    }
    return [length("hi"), length(["one"])];
  })(),
);

Sample output

[ 2, 1 ]