TypeScript
Function overloads
Learn function overloading.
Function overloads
Function overloading lets a function have multiple type signatures for different parameter patterns. You write the signatures first, then a single implementation body.
function bicim(deger: number): string;
function bicim(deger: string): string;
function bicim(deger: number | string): string {
return "Sonuç: " + deger;
}
Signatures define different call patterns, the body defines the shared implementation.
Overload implementation
The implementation signature is not visible to callers; only the overload signatures are. The implementation body must handle all cases from the signatures. This lets a single function be called in different ways.
function cevir(deger: string): number;
function cevir(deger: number): number;
function cevir(deger: string | number): number {
return Number(deger);
}
Overloading enables calling a single function with different types.
Exercise Write a function with a union type parameter
Define a function named bicim with a deger parameter of type number | string and return type string. The function should return "Sonuç: " + deger. Print the result of calling bicim(42) with console.log.
Show example solution
function bicim(deger: number | string): string {
return "Sonuç: " + deger;
}
console.log(bicim(42));
Test yourself
-
What is the purpose of function overloading?
- To make functions faster
- To prevent parameter types
- To return multiple values
- To provide multiple type signatures for different call patterns
Show answer
To provide multiple type signatures for different call patterns — Overloading lets a single function offer separate signatures for different parameter types or counts; this enables correct type checking at the call site.
-
Complete the second overload signature
function cevir(deger: string): number;
function cevir(deger: ____): number;
function cevir(deger: string | number): number {
return Number(deger);
}
Show answer
function cevir(deger: string): number;
function cevir(deger: number): number;
function cevir(deger: string | number): number {
return Number(deger);
}
-
Overloads concepts
- function f(a: number): string;
- Overload signature
- function f(a: number | string): string { ... }
- Implementation body
- Overload signatures
- Defines call patterns
- Implementation
- Handles all cases
Next lesson: Summary - Functions