How to Use Extension Methods in TypeScript ?
Last Updated :
28 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());
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.
Similar Reads
How to use express in typescript ? In this article, we will see how to use Express in TypeScript. The TypeScript is a superset of JavaScript that provides type notation with the JavaScript, so we can handle our server, and very scalable for the future. Express is web framework helps to create server-side handling with the help of Nod
2 min read
How to use property decorators in TypeScript ? Decorators are a way of wrapping an existing piece of code with desired values and functionality to create a new modified version of it. Currently, it is supported only for a class and its components as mentioned below: Class itselfClass MethodClass PropertyObject Accessor ( Getter And Setter ) Of C
4 min read
How to use Type Guards in TypeScript ? Here are the methods to use type guards in TypeScript:1. Using typeof Type GuardsThe typeof operator checks the type of a variable, primarily for primitive types like string, number, boolean, etc. JavaScriptfunction processValue(value: string | number) { if (typeof value === 'string') { console.log(
3 min read
How to use Spread Operator in TypeScript ? The spread operator in Typescript, denoted by three dots (`...`), is a powerful tool, that allows you to spread the elements of an array or objects into another array or objects. This operator makes it easy to copy arrays, combine arrays, or create shallow copies of iterable.Syntax...operatingValueE
3 min read
How to Use MathJS with TypeScript? Math.js library can be use with TypeScript to handle various mathematical tasks while getting the benefits of TypeScriptâs type safety and autocompletion. Integrating Math.js into your TypeScript project allows you to perform arithmetic, algebra, statistics, and more, with the added advantage of Typ
3 min read