【问题标题】:How to extend a primitive type in typescript?如何在打字稿中扩展原始类型?
【发布时间】: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


    【解决方案1】:

    只需添加到 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-30
      • 2020-08-18
      • 1970-01-01
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多