How to extend a primitive type in typescript?

I want to create an interface like this:

interface Show { show(): string; } function doit(s: Show) { return 'Showed: ' + s.show(); } 

Then we can use it with a new class:

 class Foo { s: string; constructor(s: string) { this.s = s; } show() { return 'Foo with "' + this.s + '"'; } } console.log(doit(new Foo('hello'))); 

I would like to do the same for Number s. In simple JavaScript, I could make the Number type, for example, execute this interface with:

 Number.prototype.show = function() { return '' + this; } 

But TypeScript does not allow me to do this:

 show.ts(18,18): error TS2094: The property 'show' does not exist on value of type 'Number'. 

Is there any way to do this?

+2
javascript interface typescript
Apr 26 '14 at 4:15
source share
1 answer

Just tell TypeScript about this by adding to Number :

 interface Number{ show():string; } Number.prototype.show = function() { return '' + this; } var foo = 123; foo.show(); 

Please note that even this is supported tightly, it is believed that this is bad practice, even in JavaScript land: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain#Bad_practice.3A_Extension_of_native_prototypes

+4
Apr 26 '14 at 5:02
source share



All Articles