AI Hints
Home›TypeScript Tutorial›Overloads and Events
TypeScript · Lesson 85 of 120

Function Overloads

Several signatures.

⏱ 2 min read▶ Video at 1:06:12🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Some functions return different types, depending on their arguments. Overloads list each allowed way to call the function, with its own return type.

Function Overloads
From the video: Function Overloads
  • Different arguments
  • Different results
  • Overloads

Find by id or by name

The first two lines are the overloads. A number returns one order. A string returns a list of orders. The real function below handles both. Run it.

app.tstypescript
type Order = { id: number; customer: string };
const ORDERS: Order[] = [{ id: 1042, customer: "Sam" }, { id: 1043, customer: "Sam" }];

function find(id: number): Order | undefined;
function find(customer: string): Order[];
function find(key: number | string) {
  return typeof key === "number"
    ? ORDERS.find(o => o.id === key)
    : ORDERS.filter(o => o.customer === key);
}

const one = find(1042);       // Order | undefined
const many = find("Sam");     // Order[]
console.log(one?.id, many.length);
Output
1042 2

Use them sparingly

Overloads are great when the return type truly depends on the argument type. Often, two clearly named functions are simpler. Like find by id, and find by customer.

keyvalue
Goodreturn depends on input
Simplertwo functions
Orderspecific first
Bodyhandles all cases

Summary

Overloads describe several ways to call one function. Next, type safe events.

Key takeaways
  • Overload signatures
  • Implementation
  • Or two functions
Next up: Type-Safe Events — an event map