Skip to content
dreamcode
dreamcode
Map
Overloads
Lesson 24 of 26
+15 XP on finish
TS EXPERTChapter 4 · TS Expert

Function Overloads

Overloads describe a function that returns different types for different arguments. Write several signatures without bodies, then one implementation whose signature covers them all. Callers only see the overload signatures, so every call gets an exact return type: parse("42") returns a number, and parse(["1", "2"]) returns number[].

Worked example

How it reads

  • The first two lines are what callers see
  • The implementation signature must accept every overload's arguments
  • one is a number and many is a number[], no casts needed
Cloud tip: If a union parameter and a union return type would do, prefer that. Use overloads when the return type depends on the argument type.
index.ts
TYPESCRIPT
type-checked, then run in your browser
Console
Run your code to see its output here.
YOUR TURN

Add two overload signatures above the implementation: format(value: number, digits: number): string; and format(value: Date): string;. Give the implementation an optional digits and use toFixed(digits) for numbers. Log format(3.14159, 2): 3.14.

Press Run to check your work.