How to Use Extension Methods in TypeScript ?
Last Updated :
24 Apr, 2025
Typescript developers in general face situations where they need to add functionality to existing classes. The extension method in typescript helps in extending the functionality of predefined classes or third-party libraries without modifying the source code.
In Simple words, Extension methods in TypeScript are a way to add new functionality to existing classes or interfaces without altering their original definitions. They are declared as standalone functions but can be used as if they were methods of the extended class or interface. This allows for more modular and maintainable code.
Syntax
declare global {
interface ClassNameOrInterface<T> {
methodName(...args: any[]): ReturnType;
}
}
Example 1: This code declares an extension method sum
for the Array
class in TypeScript. It calculates the sum of all the elements in the array. The sum
method is then used on an array of numbers to calculate the sum of its elements.
JavaScript
// Declare the Extension Method
function sum(this: number[]): number {
return this.reduce((acc, curr) => acc + curr, 0);
}
// Declare the Extension
declare global {
interface Array<T> {
sum(): number;
}
}
// Implement the Extension
Array.prototype.sum = sum;
// Use the Extension Method
const numbers: number[] = [5, 6, 7, 2, 3];
console.log(numbers.sum());