Jklf Jklf - 1 month ago 11
Javascript Question

Extending Typescript Type with custom method in angular 2

I am building an angular 2 project with the CLI.

I need to add a custom method to the String type like this.

interface String {
foo(): number;
}

String.prototype.foo= function() {
return 0;
}


Is that correct and where can I put this code in the project to make it works.The compiler still complains.
Can anyone help me to have the expected behaviour ?

Answer

You need to tell typescript about this, if you are working with angular cli you can put this in your typings.d.ts file:

  interface String {
    foo(): number;
  }