Categories
TypeScript Answers

How to extend String prototype with TypeScript?

Spread the love

Sometimes, we want to extend String prototype with TypeScript.

In this article, we’ll look at how to extend String prototype with TypeScript.

How to extend String prototype with TypeScript?

To extend String prototype with TypeScript, we can add our entries to the String interface in a .d.ts file in our project.

For instance, we write

declare global {
  interface String {
    padZero(length: number): string;
  }
}

in a .d.ts file to add the padZero method into the String interface.

Then we can add the padZero method into the String prototype without errors by writing

String.prototype.padZero = function (this: string, length: number) {
  const s = this;
  while (s.length < length) {
    s = "0" + s;
  }
  return s;
};

We add this as a parameter of the function and set it to string.

The this parameter will be discarded when the code is compiled into JavaScript.

Conclusion

To extend String prototype with TypeScript, we can add our entries to the String interface in a .d.ts file in our project.

2 replies on “How to extend String prototype with TypeScript?”

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.