TypeScript example

How to overload a function in TypeScript

8 min read Updated Nov 2026 Runs in an isolated runtime
Quick answer

Write the overload signatures (declarations with no body) one after another, then one implementation whose parameters accept every overload: function getUser(id: number): User | undefined;, function getUser(ids: number[]): User[];, then function getUser(x: number | number[]): User | User[] | undefined { … }. Inside the body, tell the cases apart at runtime with typeof or Array.isArray. Two functions with the same name and their own bodies fail with error TS2393: Duplicate function implementation.

JavaScript has no function overloading: a function is one object under one name, and the types TypeScript adds are erased before the code runs. So TypeScript overloads are a compile-time feature. You describe each way the function can be called as a separate signature, and one implementation handles all of them by checking its arguments. Callers get a precise return type for each form, which a single union signature can't give them. The sections below cover the syntax, the error you get when you write overloads the Java or C# way, the order rules, constructors and static factories, overloads in types, arrow functions and class methods, and when you shouldn't overload at all. Each example runs on this page: hit Run, then edit the code and run it again.

1Overload signatures plus one implementationRecommended

List the overload signatures first, each ending in a semicolon, then write the implementation directly below them under the same name. Callers only see the overloads: the implementation's own signature is hidden, so it can be as broad as it needs to be. It must accept every overload's parameters and return something every overload's return type allows. Here a single id returns one user and an array of ids returns an array, and the implementation tells them apart with Array.isArray.

overloads.ts
interface User {
    id: number;
    name: string;
}

const users: User[] = [
    { id: 1, name: "Ada" },
    { id: 2, name: "Grace" },
    { id: 3, name: "Linus" },
];

// Overload signatures: the only ones callers see
function getUser(id: number): User | undefined;
function getUser(ids: number[]): User[];
// Implementation signature: hidden, and it must cover every overload
function getUser(idOrIds: number | number[]): User | User[] | undefined {
    if (Array.isArray(idOrIds)) {
        return users.filter((u) => idOrIds.includes(u.id));
    }
    return users.find((u) => u.id === idOrIds);
}

const one = getUser(2);          // User | undefined
const many = getUser([1, 3]);    // User[]: no cast, no check needed

console.log(one?.name);
console.log(many.map((u) => u.name).join(", "));
console.log(getUser(9));
console.log(getUser([]).length);

Output

The run prints Grace, Ada, Linus, undefined for the missing id and 0 for the empty list. The point is the types: many is User[], so many.map compiles without a cast or an Array.isArray check at the call site. With one signature returning User | User[] | undefined, every caller would have to narrow the result first. The overloads are only for the checker: the compiled JavaScript contains just the implementation.

2Why two bodies fail: Duplicate function implementation

The most common first attempt, and the top Stack Overflow question on the topic, writes overloads the way Java or C# does: two complete functions with the same name and different parameter types. TypeScript rejects it, because the JavaScript it compiles to can only hold one function under that name. This embed fails on purpose: the type errors stop the run before anything executes.

duplicate.ts
// Two bodies with the same name, the way Java or C# overloads look
function describe(value: string): string {
    return `text of length ${value.length}`;
}

function describe(value: number): string {
    return `number ${value.toFixed(2)}`;
}

console.log(describe("hello"));
console.log(describe(3.14159));

Output

Both functions are flagged with error TS2393: Duplicate function implementation., and the last call adds error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'. because the checker only knows the first declaration. In plain JavaScript the second function declaration would silently replace the first. The fix is section 1: keep the two signatures without bodies and merge the bodies into one implementation that branches on typeof value.

3Order overloads from specific to general

TypeScript checks a call against the overloads from top to bottom and uses the first one that matches, so the specific signatures go first. Because the implementation signature is hidden, a caller holding a union such as string | string[] matches none of the specific overloads. If those callers exist, add a union overload as the last one.

order.ts
// The most specific overloads first: TypeScript takes the first match
function toNumbers(input: string): number;
function toNumbers(input: string[]): number[];
// A union overload last, for callers that hold string | string[]
function toNumbers(input: string | string[]): number | number[];
function toNumbers(input: string | string[]): number | number[] {
    return Array.isArray(input) ? input.map(Number) : Number(input);
}

const page = toNumbers("2");             // number
const ids = toNumbers(["7", "8", "9"]);  // number[]
console.log(page.toFixed(1), ids.length);

// Query values can be one string or several: only the union overload fits
const query: Record<string, string | string[]> = { page: "2", ids: ["7", "8", "9"] };
for (const key of Object.keys(query)) {
    const value: string | string[] = query[key];
    console.log(key, toNumbers(value));
}

Output

It prints 2.0 3, then page 2 and ids [ 7, 8, 9 ]. Delete the union overload and the loop stops compiling with error TS2769: No overload matches this call., followed by one reason per overload, even though the implementation accepts exactly that type. Move the union overload to the top instead and it wins every call, so page becomes number | number[] and you get error TS2339: Property 'toFixed' does not exist on type 'number | number[]'. Last, an implementation that doesn't cover an overload, such as function toNumbers(input: string) under a string[] overload, fails with error TS2394: This overload signature is not compatible with its implementation signature.

4Overload a constructor, or use a static factory

A class has one constructor, and it overloads the same way: signatures without bodies, then one constructor that accepts them all, usually through optional parameters. Constructor signatures have no return type. When two forms would take the same parameter types, such as (x, y) and (radius, angle), overloads can't tell them apart. A static factory method with its own name can, and it reads better at the call site.

constructor.ts
interface Coords {
    x: number;
    y: number;
}

class Point {
    x: number;
    y: number;

    // Constructor overloads: same rules, no return types
    constructor();
    constructor(x: number, y: number);
    constructor(coords: Coords);
    constructor(xOrCoords?: number | Coords, y?: number) {
        if (typeof xOrCoords === "object") {
            this.x = xOrCoords.x;
            this.y = xOrCoords.y;
        } else {
            this.x = xOrCoords ?? 0;
            this.y = y ?? 0;
        }
    }

    // (radius, angle) is also (number, number): a named factory avoids the clash
    static fromPolar(radius: number, angle: number): Point {
        return new Point(radius * Math.cos(angle), radius * Math.sin(angle));
    }

    toString(): string {
        return `(${this.x}, ${this.y})`;
    }
}

console.log(String(new Point()));
console.log(String(new Point(3, 4)));
console.log(String(new Point({ x: -1, y: 5 })));

const p = Point.fromPolar(2, Math.PI / 2);
console.log(p.x.toFixed(2), p.y.toFixed(2));

Output

The three constructor forms print (0, 0), (3, 4) and (-1, 5), and the polar point is 0.00 2.00. Callers can't use the implementation signature's looser shape: new Point(1) matches only the one-argument overload and fails with error TS2345: Argument of type 'number' is not assignable to parameter of type 'Coords'. Every field is assigned on every path, so the class also compiles with strict on. If the forms multiply, an options object (one parameter with optional properties) is usually easier to read than five constructor overloads.

5When a union or an optional parameter is enough

Overloads earn their keep when the return type depends on the arguments. When it doesn't, the TypeScript handbook's advice is to prefer a union parameter: it is shorter, and it accepts union-typed arguments, which overloads only do if you add a union overload by hand. Likewise, two overloads that differ only by a trailing parameter are one signature with an optional or default parameter.

union.ts
// Overloads add nothing when the return type is the same for every input
function widthOf(value: string): number;
function widthOf(value: unknown[]): number;
function widthOf(value: string | unknown[]): number {
    return value.length;
}

// One union parameter says the same thing, and accepts the union too
function lengthOf(value: string | unknown[]): number {
    return value.length;
}

// An optional parameter replaces greet(name) + greet(name, greeting)
function greet(name: string, greeting: string = "Hello"): string {
    return `${greeting}, ${name}!`;
}

console.log(widthOf("abcd"), widthOf([1, 2]));

const inputs: (string | number[])[] = ["abcd", [1, 2, 3]];
for (const input of inputs) {
    console.log(lengthOf(input));    // widthOf(input) would not compile
}

console.log(greet("Ada"));
console.log(greet("Grace", "Welcome"));

Output

Both versions print 4 2 for direct calls, and the loop prints 4 and 3 through the union version. Calling widthOf(input) in the loop fails with error TS2769: No overload matches this call.: the overloads promised nothing extra and cost flexibility. The greetings print Hello, Ada! and Welcome, Grace!. To check what a variable's type is at runtime rather than at compile time, see check a type at runtime.

6Overloads in a type, an arrow function and a method

A type or interface can list several call signatures; that is how you describe an overloaded function as a value, for a callback or a property. An arrow function can't declare overloads itself, because it has exactly one signature. The clean way to fill such a type is a function declaration with matching overloads. An arrow needs a type assertion. Class and interface methods overload with the same syntax as functions, and string literal parameters make a handy key-to-type lookup.

call-signatures.ts
// A function type with two call signatures
interface Converter {
    (value: string): number;
    (value: number): string;
}

// A function declaration with matching overloads fits the type as it is
function convertFn(value: string): number;
function convertFn(value: number): string;
function convertFn(value: string | number): string | number {
    return typeof value === "string" ? Number(value) : String(value);
}
const convert: Converter = convertFn;

// An arrow function has one signature, so it needs an assertion
const convertArrow = ((value: string | number) =>
    typeof value === "string" ? Number(value) : String(value)) as Converter;

const n = convert("42");         // number
const s = convertArrow(7);       // string
console.log(n + 1, typeof n);
console.log(s.padStart(3, "0"), typeof s);

// Methods overload the same way, here on string literal keys
class Settings {
    private values = { port: 8080, host: "localhost" };

    get(key: "port"): number;
    get(key: "host"): string;
    get(key: "port" | "host"): number | string {
        return this.values[key];
    }
}

const settings = new Settings();
console.log(settings.get("port") + 1, settings.get("host").toUpperCase());

Output

It prints 43 number, 007 string and 8081 LOCALHOST: each call got the return type of the signature it matched. Without the as Converter, annotating the arrow as Converter fails with error TS2322: Type '(value: string | number) => string | number' is not assignable to type 'Converter'. The assertion silences that check, so a wrong body would compile too; prefer the function declaration when you can. To type a single-signature callback, see type a callback function.

7Which should you use?

ApproachReturn type per callAccepts a union argumentBest for
Overload signaturesYesOnly with a union overloadReturn type that depends on the arguments
Union parameterNo, one shared typeYesSame return type for every input: the default
Optional / default parameterNo, one shared typeYesForms that differ by a trailing argument
Static factory methodYes, one per namePer methodConstructors whose forms share parameter types
Interface call signaturesYesOnly with a union signatureAn overloaded function passed around as a value
Two bodies, same nameTS2393 errorn/aNothing: JavaScript keeps one function per name

Frequently asked questions

Does TypeScript support function overloading?

Yes, but only at compile time. You write several overload signatures without bodies and one implementation below them, and the checker picks the matching signature for each call. At runtime there is a single JavaScript function, so the implementation has to inspect its arguments with typeof, Array.isArray or instanceof to decide what to do.

Why do I get "Duplicate function implementation"?

Because two declarations with the same name both have a body. TypeScript allows any number of overload signatures but only one implementation, since the compiled JavaScript can hold one function per name. Remove the bodies from all but one declaration, widen that one to accept every form (for example value: string | number), and branch inside it.

Why does a call that the implementation accepts fail with "No overload matches this call"?

The implementation signature is not visible to callers; only the overload signatures are. A value of type string | string[] matches neither (input: string) nor (input: string[]), so the call fails even if the implementation takes string | string[]. Add a union overload as the last signature, or replace the overloads with one union parameter if the return type is the same anyway.

How do I overload an arrow function?

An arrow function has one signature, so it cannot declare overloads. Describe the overloads in a type with several call signatures, such as interface Converter { (value: string): number; (value: number): string; }, then assign a function declaration that has matching overloads, or assert the arrow with as Converter. The assertion turns off the check that the body matches, so the function declaration is safer.

Can a TypeScript class have multiple constructors?

Not as separate bodies. A class has one constructor, which can have several overload signatures above it, with optional or union-typed parameters in the implementation. When two forms take the same parameter types, such as (x: number, y: number) and (radius: number, angle: number), use static factory methods like Point.fromPolar(radius, angle) instead, since overloads cannot tell them apart.

Should I use overloads or a union type?

Use a union parameter when every form returns the same type: it is shorter and also accepts union-typed arguments. Use overloads when the return type depends on the argument, such as one id returning User and an array of ids returning User[]. Generic functions with conditional return types can express the same mapping, but their implementations usually need casts, so overloads are often the clearer choice.

Run it yourself

Open any of these in the full TypeScript editor to tweak, run and share.

TypeScript playground