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

问题描述 投票:0回答:1

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

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

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

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

interface String {
  frenchQuote(): string
}

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

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

使用TypeScript版本 3.7

typescript prototypal-inheritance
1个回答
0
投票

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

declare global {
  interface String {
    frenchQuote(): string
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.