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'd like to do the same thing for Numbers. In plain JavaScript I could make the type Number, for example, satisfy this interface with:
Number.prototype.show = function() {
return '' + this;
}
But TypeScript doesn't let me do this:
show.ts(18,18): error TS2094: The property 'show' does not exist on value of type 'Number'.
Is there a way to do this?
Just tell TypeScript about it by adding to Number :
interface Number{
show():string;
}
Number.prototype.show = function() {
return '' + this;
}
var foo = 123;
foo.show();
Please note that even tough it is supported it is considered bad practice to do so 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With