代码之家  ›  专栏  ›  技术社区  ›  Pavel_K

扩展ES6模块中的对象原型时,类型“Object”上不存在属性

  •  0
  • Pavel_K  · 技术社区  · 6 年前

    //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

    1 回复  |  直到 6 年前
        1
  •  1
  •   Titian Cernicova-Dragomir    6 年前

    您声明的接口不在全局范围内,它在当前模块中。您需要在全局中声明它:

    import { Test } from "./mod2"; //LINE X
    declare global {
      interface Object {
        GetFooAsString(): string;
      }
    }
    
    Object.prototype.GetFooAsString = function () {
      return this.GetFoo().toString();
    }
    

    发生这种情况的原因是,在添加导入或导出之前,文件被认为是一个简单的脚本,所有内容都在全局范围内。添加导入/导出时,它将成为一个模块,因此所有内容都在模块范围内。