Open In App

How to Use Extension Methods in TypeScript ?

Last Updated : 08 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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());


Output:

23

Example 2: This TypeScript code declares an extension method capitalize for the String class. It capitalizes each letter of a string by splitting the string into an array of characters, mapping over each character to capitalize it, and then joining the characters back into a string. The capitalize method is then used on a string to capitalize each letter.

Javascript




// Declare the Extension Method
function capitalize(this: string): string {
  return this.split("")
    .map((char) => char.toUpperCase())
    .join("");
}
 
// Declare the Extension
declare global {
  interface String {
    capitalize(): string;
  }
}
 
// Implement the Extension
String.prototype.capitalize = capitalize;
 
// Use the Extension Method
const str: string = "hello world";
console.log(str.capitalize());


Output:

HELLO WORLD

Conclusion

In conclusion, extension methods in TypeScript provide a way to add functionality to existing classes and interfaces without modifying their original definitions. This is particularly useful when working with built-in classes and interfaces such as Array and String. We can easily add new methods to these classes and interfaces by using extension methods, improving their usability, and reducing code duplication.

When using extension methods, it is important to follow best practices, such as properly encapsulating the implementation of the method and avoiding clashes with existing methods or properties. With the right approach, extension methods can greatly enhance the functionality and usability of your TypeScript code.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads