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:
I was able to get it working with no TS errors (1.8.9), Angular2 (2.0.0-beta.12) errors, and working function call using the following template:
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "system",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
},
"exclude": [
"node_modules",
"typings/main",
"typings/main.d.ts"
]
}
Next, create (if one doesn't exist) a global.d.ts file local to your project:
global.d.ts (local to project, not main TS file of same name)
export {}
declare global {
interface String {
calcWidth(): number;
}
}
extensions.ts (entire file)
export {}
//don't redefine if it's already there
if (!String.prototype.hasOwnProperty('calcWidth')) {
String.prototype.calcWidth = function (): number {
//width calculations go here, but for brevity just return length
return this.length;
}
}
Then in your whatever your first System.import(filename) is (mine is main.ts). Just use once:
import './extensions' //or whatever path is appropriate
...
...
Now, throughout your app you can use your interface:
var testString = 'fun test';
console.log(testString.calcWidth());
Produces console output:
8
Hope this is helpful.
Instead of importing the code in html just put this at the top of your code:
import './utils/extensions';
Just replace it with your path to the file.
Here are some more resources on modules and imports:
TypeScript docs
MDN docs