{

Typescript extension methods to existing types with examples


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))
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.