Home Extension methods in typescript (system)
Reply: 0

Extension methods in typescript (system)

user1531
1#
user1531 Published in April 23, 2018, 5:23 pm

In my angular2 project I'm trying to extend the prototype of the string class using typescript. This is my code:

interface String 
{
    startsWith(s:string);
    contains(s:string);
    containsOr(s1:string, s2:string);
}

String.prototype.startsWith = function (s:string):boolean {
    return this.indexOf (s) === 0;
}
String.prototype.contains = function (s:string):boolean {
    return this.indexOf(s) > 1;
}
String.prototype.containsOr = function (s1:string, s2:string):boolean {
    return this.indexOf(s1) > 1 || this.indexOf (s2) > 1;
}

With this code the project compiles (also the content assist of Visual Studio Code assists me) but at run-time I get a 'contains is not defined'.

What I'm doing wrong?

Thanks a lot

PS: this is my tsconfig:

{
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "outDir": "wwwroot/app/source/"
  },
  "exclude": [
    "node_modules",
    "bower_components",
    "wwwroot",
    "typings/main",
    "typings/main.d.ts"
  ]
}

EDIT

I noticed that importing the js file in index.html it works, but I don't like this approach.

<script src="app/source/utils/extensions.js"></script>
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.303674 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO