How to extend a primitive type in typescript?

China☆狼群 提交于 2019-12-24 05:47:10

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/23306562/how-to-extend-a-primitive-type-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!