Borislav Hadzhiev
Sat Feb 26 2022·2 min read
Photo by Brooke Cagle
To extend String.prototype in TypeScript:
string.extensions.ts
file.String
interface and add the extension method.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
, 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.
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.
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.