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?”
After creating the .d.ts file, where do we save it?
You can put it anywhere in the project folder.