【发布时间】:2014-06-11 23:04:34
【问题描述】:
我想创建一个这样的界面:
interface Show {
show(): string;
}
function doit(s: Show) {
return 'Showed: ' + s.show();
}
然后我们可以将它与一个新类一起使用:
class Foo {
s: string;
constructor(s: string) {
this.s = s;
}
show() {
return 'Foo with "' + this.s + '"';
}
}
console.log(doit(new Foo('hello')));
我想为Numbers 做同样的事情。例如,在纯 JavaScript 中,我可以使类型 Number 满足此接口:
Number.prototype.show = function() {
return '' + this;
}
但是 TypeScript 不允许我这样做:
show.ts(18,18): error TS2094: The property 'show' does not exist on value of type 'Number'.
有没有办法做到这一点?
【问题讨论】:
标签: javascript interface typescript