How to Extend String.prototype in TypeScript


Borislav Hadzhiev

Last updated: Feb 26, 2022


Photo from Unsplash

Extend String.prototype in TypeScript #

To extend String.prototype in TypeScript:

  1. Create a string.extensions.ts file.
  2. Extend the String interface and add the extension method.
  3. Import the extension method as import './string.extensions' before using it.

Here is the content of string.extensions.ts:

interface String { prefix(pre: string): string; } String.prototype.prefix = function (pre: string) { return pre + this; };

And here is how we import and use the new prefix method on the String prototype:

import './string.extensions'; const str = 'world'; console.log(str.prefix('hello ')); // 👉️ "hello world"

If I run my index.ts file, we can see that the prefix method gets successfully invoked.

string prototype extended

We declared a new interface String, which will get merged with the original String interface.

In the interface, we created a prefix method, which adds leading characters to the original string and returns the result.

Make sure to use a named function when extending the prototype, and not an arrow function, because arrow functions use the this of the enclosing scope, which is not what you want.

You could use this approach to extend String.prototype with any method. Here is an example of a method that adds the passed in strings together.

This is the code in the string.extensions.ts file:

interface String { add(...strings: string[]): string; } String.prototype.add = function (...strings) { return this + strings.join(''); };

And here is the index.ts file, which imports string.extensions and makes use of the add method.

import './string.extensions'; const str = 'hello'; // 👇️ "hello one two three" console.log(str.add(' one', ' two', ' three'));

Make sure to specify the correct path when importing the string.extensions.ts module.

When overriding String.prototype, make sure your methods are not interfering with built-in method names, unless intentionally overriding them (which can be confusing).

Here is an example of how you would override the built-in toLowerCase() method.

interface String { toLowerCase(): string; } String.prototype.toLowerCase = function () { return this.toUpperCase(); };

And here is the code in our index.ts file.

import './string.extensions'; const str = 'Hello World'; // 👇️ "HELLO WORLD" console.log(str.toLowerCase());

Note that overriding built-in methods is confusing and should generally be avoided.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.