如何从TypeScript中的其他模块添加到类型原型?

时间:2020-02-06 22:30:40

标签: typescript prototypal-inheritance

假设我想将此方法添加到String上:

String.prototype.frenchQuote = function() {
  return '« ' + this + ' »';
}

TypeScript会抱怨frenchQuote上没有String方法。

在线,可以找到许多建议,然后像这样声明它:

interface String {
  frenchQuote(): string
}

但是,TypeScript将此interface标记为未使用,并且仍然抱怨该方法不存在。

是否有一种新方法来增强导入类型或内置类型的签名?

使用TypeScript版本 3.7

1 个答案:

答案 0 :(得分:0)

谢谢@pushkin的提示。解决方案是向TS发出interface是全局的信号:

declare global {
  interface String {
    frenchQuote(): string
  }
}