Sobes.tech
Junior — Middle

What are the differences between function overloading and overriding in TypeScript?

sobes.tech AI

Answer from AI

In TypeScript:

  • Function Overloading — is the declaration of multiple signatures of a single function with different parameters, but with one implementation. It allows calling a function with different sets of arguments, while the compiler understands which return type to expect.

  • Overriding — is an object-oriented programming mechanism where a subclass provides its own implementation of a method that is already defined in the base class.

Example of overloading:

function combine(a: string, b: string): string;
function combine(a: number, b: number): number;
function combine(a: any, b: any): any {
  return a + b;
}

const result1 = combine("Hello, ", "world"); // string
const result2 = combine(1, 2); // number

Example of overriding:

class Animal {
  speak() {
    console.log("Animal speaks");
  }
}

class Dog extends Animal {
  speak() {
    console.log("Dog barks");
  }
}

const dog = new Dog();
dog.speak(); // "Dog barks"

Summary:

  • Overloading — different ways to call the same function.
  • Overriding — replacing the behavior of a method in a subclass.