CodeBlanks Logo Icon CodeBlanks

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.

Practice 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.

Starter code

index.ts
// bicim adında bir fonksiyon tanımla
// deger parametresi number | string, dönüş türü string olsun
// "Sonuç: " + deger değerini döndür
// bicim(42) sonucunu yazdır

Sample solution

index.ts
function bicim(deger: number | string): string {
    return "Sonuç: " + deger;
}
console.log(bicim(42));

Expected output

Sonuç: 42

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 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 Correct answer

Explanation: Overloading lets a single function offer separate signatures for different parameter types or counts; this enables correct type checking at the call site.

2 Complete the second overload signature

Question
function cevir(deger: string): number;
function cevir(deger: ____): number;
function cevir(deger: string | number): number {
  return Number(deger);
}
Answer
function cevir(deger: string): number;
function cevir(deger: number): number;
function cevir(deger: string | number): number {
  return Number(deger);
}

Explanation: The second signature defines a call pattern accepting <code>number</code>; <code>string</code> would duplicate the first signature, and <code>boolean</code> and <code>void</code> make no sense for number conversion.

3 Overloads concepts

Term Meaning
function f(a: number): string; Overload signature
function f(a: number | string): string { ... } Implementation body
Overload signatures Defines call patterns
Implementation Handles all cases

All lessons in Beginner