Typescript extension methods to existing types with examples

Swift and Dart languages provide extensions as part of their language features. Extension methods offer additional functionality to existing classes by introducing new methods to them. This enables the addition of new methods to existing types such as Numbers and Strings.

In JavaScript, prototypes are utilized to add extra functionality. Similarly, prototypes can be used for extending existing classes.

TypeScript Extension Methods Example

The following demonstrates how to add an extension method to an existing built-in type:

  • First, define the functionality within global scope modules using declare global.
  • Create an interface containing 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 functionality to convert a Number to a String.

In this example, we declare an external module using Augmentations within the global scope.

We create an interface method containing the toString abstract method. We provide an implementation for this method and add it to the prototype.

Here’s 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

Arrays do not inherently possess a method that returns true if an element exists.

Here is an example of extending the Array type in TypeScript.

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];

This allows you to check if an element exists within the array by utilizing the exists method.