我尝试扩展JS本机String类添加新方法但是得到TS2339错误。
interface String {
transl(): string;
}
String.prototype.transl = function() { // TS2339: Property 'transl' does not exist on type 'String'.
return 'xxx';
};
'ff'.transl();
答案 0 :(得分:1)
您的代码在技术上是正确的,并且在TypeScript操场中工作,这使我相信问题是由于在模块中包含此代码而引起的。
在模块或命名空间中编写接口时,它会为该模块或命名空间的命名上下文做出贡献。即您可能正在向本地命名上下文添加名为String
的新接口,而不是将您的接口声明与全局String
接口合并。
您可以通过将接口放在全局上下文中来解决此问题,因此它具有与lib.d.ts
文件中的接口相同的公共根。或者在模块中使用declare global
:
declare global {
interface String {
transl(): string;
}
}
String.prototype.transl = function () {
return 'xxx';
};
'ff'.transl();