Angular2 & Typescript: How to add a line extension / prototype method

I want to add the extension method format() to String . Therefore, I expect that I can use String.format wherever in my project. I followed the recommendation of this topic , but it does not help. I got this error: enter image description here

Can anybody help me?

Thanks in advance.

ps: I want to add an extension method, as I did in angular 1.xx

enter image description here


Edit

use declare global will not receive an error.

 declare global { interface String { format(): string; }} String.prototype.format = function () :string { var result = arguments[0]; for (var i = 0; i < arguments.length - 1; i++) { var reg = new RegExp("\\{" + i + "\\}", "gm"); result = result.replace(reg, arguments[i + 1]); } return result;} 

How do we use String.format('<img alt="{0}" title="{0}" src="{1}" />', name, id); Since format does not require parameters

+7
angular extension-methods typescript
source share
1 answer

Based on this playground , it works great.

This probably won't work for you because you are probably using modules (import / export), in which case you need to do this in a global increase :

 declare global { interface String { foo(): number; } } 

Then you will not get an error when adding foo to the prototype.


Edit

It sounds like you want a static function on a String , so you need to do this:

 declare global { interface StringConstructor { format(): string; } } String.format = function (...args: string[]) { ... } 

I also added ...args: string[] to the signature, which tells the compiler that the function expects any number of lines as arguments.

+4
source share

All Articles