I am trying to transcript existing JavaScript code into TypeScript and ran into a problem with extending builtin objects by Object.defineProperty
, e.g. String.prototype
.
Object.defineProperty(String.prototype, 'testFunc',
{ value: function():string {return 'test';}
});
var s1:string = 'abc'.testFunc(); // Property 'testFunc' does not exist on type 'string'
var s2:string = String.prototype.testFunc(); // Property 'testFunc' does not exist on type 'String'
Object.defineProperty(Object, 'testFunc',
{ value: function():string {return 'test';}
});
var s:string = Object.testFunc(); // Property 'testFunc' does not exist on type 'ObjectConstructor'
It gets properly translated into JavaScript, however, Netbeans 8.1 with a TypeScript plugin claims the errors listed as comments above.
All of my confused experiments with declare
and interface
did not match any proper syntax. I have no idea how to get it work.
How can I extend builtin objects in TypeScript and make the IDE accepting it?
After 1001 try'n'errors I've figured out a working solution. By now it seems to do what I want.
interface String { strFunc:Function; }
Object.defineProperty(String.prototype, 'strFunc',
{ value: function():string {return 'test';}
});
var s1:string = 'abc'.strFunc();
var s2:string = String.prototype.strFunc();
interface ObjectConstructor { objFunc:Function; }
Object.defineProperty(Object, 'objFunc',
{ value: function():string {return 'test';}
});
var s:string = Object.objFunc();
// objFunc should not work on strings:
var s:string = 'a string instance'.objFunc(); // Property 'testFunc' does not exist on type 'string'