lim*_*imp 3 javascript interface typescript
我想创建一个这样的界面:
interface Show {
show(): string;
}
function doit(s: Show) {
return 'Showed: ' + s.show();
}
Run Code Online (Sandbox Code Playgroud)
然后我们可以将它与一个新类一起使用:
class Foo {
s: string;
constructor(s: string) {
this.s = s;
}
show() {
return 'Foo with "' + this.s + '"';
}
}
console.log(doit(new Foo('hello')));
Run Code Online (Sandbox Code Playgroud)
我想为Numbers 做同样的事情。Number例如,在纯 JavaScript 中,我可以使 type满足此接口:
Number.prototype.show = function() {
return '' + this;
}
Run Code Online (Sandbox Code Playgroud)
但 TypeScript 不允许我这样做:
show.ts(18,18): error TS2094: The property 'show' does not exist on value of type 'Number'.
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?
只需添加以下内容即可告诉 TypeScript Number:
interface Number{
show():string;
}
Number.prototype.show = function() {
return '' + this;
}
var foo = 123;
foo.show();
Run Code Online (Sandbox Code Playgroud)
请注意,即使它受到支持,即使在 JavaScript 领域,这样做也被认为是不好的做法:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain#Bad_practice.3A_Extension_of_native_prototypes
| 归档时间: |
|
| 查看次数: |
3773 次 |
| 最近记录: |