Typescript extension methods to existing types with examples
- Admin
- Sep 20, 2023
- Typescript
Swift and dart languages provide extensions as part of the language. Extension methods are added extra functionality to existing classes. It provides extra new methods to existing classes. You can add new methods to existing types such as Number, and String Dates.
Javascript provides prototypes to add extra functionality, Similarly, You can use the prototype for existing classes.
Typescript extension methods example
The following is a way to add an extension method to the existing Inbuilt type.
-
First, add the functionality in Global scope modules using declare global
-
Create an interface that contains a Function to return the value
-
provide the prototype to an existing class and attach the new function to it
For example, let’s add the functionality of converting a Number to a String.
In this, Declared external module using Augmentations global scope.
- Created Interface methods that contain the toString abstract method
- provide an implementation for this method, and add it to the prototype
Here is an example
export {};
declare global {
interface Number {
toString(): String;
}
}
Number.prototype.toString = function (this: number) {
return String(this);
};
const number = 11;
const str = number.toString();
console.log(str); //"11"
console.log(typeof str); // String
How to add an extension method to an Array type
Array does not have a exists method that returns true if an element exists.
Here is a Typescript Array extension example
interface Array<T> {
exists(item: T): boolean;
}
Array.prototype.exists = function (element) {
return this.some((obj) => element == obj);
};
let arr = [1, 2, 3, 4, 5, 6];
console.log(arr.exists(1));