Typescript 扩展ES6模块中的对象原型会使类型';上不存在属性;对象';
我有两个模块——mod1.ts和mod2.tsTypescript 扩展ES6模块中的对象原型会使类型';上不存在属性;对象';,typescript,prototype,Typescript,Prototype,我有两个模块——mod1.ts和mod2.ts //mod1.ts import {Test} from "./mod2"; //LINE X interface Object { GetFooAsString(): string; } Object.prototype.GetFooAsString = function () { return this.GetFoo().toString(); } //mod2.ts export class Test { te
//mod1.ts
import {Test} from "./mod2"; //LINE X
interface Object {
GetFooAsString(): string;
}
Object.prototype.GetFooAsString = function () {
return this.GetFoo().toString();
}
//mod2.ts
export class Test {
test(): void {
console.log("Test");
}
}
如果我在mod1.ts处注释X行并按如下方式编译:tsc--module ES2015--target ES2015 mod1.ts
,则一切正常。但是,如果我取消注释第X行并编译两个模块:tsc--module ES2015--target ES2015 mod1.ts mod2.ts
mod1.ts:7:18 - error TS2339: Property 'GetFooAsString' does not exist on type 'Object'.
7 Object.prototype.GetFooAsString = function () {
~~~~~~~~~~~~~~
如何解释和修复它?我使用TypeScript 3.0.1您声明的接口不在全局范围内,它在当前模块中。您需要在全局中声明它:
import { Test } from "./mod2"; //LINE X
declare global {
interface Object {
GetFooAsString(): string;
}
}
Object.prototype.GetFooAsString = function () {
return this.GetFoo().toString();
}
发生这种情况的原因是,在添加导入或导出之前,文件被视为一个简单的脚本,所有内容都在全局范围内。添加导入/导出时,它将成为一个模块,因此所有内容都在模块范围内