如何在打字稿中扩展原始类型?

时间:2014-04-26 04:15:39

标签: javascript interface typescript

我想创建一个这样的界面:

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')));

我想对Number做同样的事情。在普通的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'.

有办法做到这一点吗?

1 个答案:

答案 0 :(得分:4)

通过添加到Number

告诉TypeScript
interface Number{
    show():string;
}

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

var foo = 123;
foo.show();

请注意,即使在JavaScript版本中,即使在强大的版本支持下也是不好的做法:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain#Bad_practice.3A_Extension_of_native_prototypes

相关问题