在 ES6 模块中扩展对象原型会导致“对象”类型不存在属性

帕维尔_K

我有两个模块 - 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 {

    test(): void {
       console.log("Test");
    } 
}

如果我在 mod1.ts 注释 LINE X 并以这种方式编译它:tsc --module ES2015 --target ES2015 mod1.ts那么一切正常。但是,如果我取消注释 LINE 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 () {
                   ~~~~~~~~~~~~~~

如何解释和修复?我使用打字稿 3.0.1

提香·切尔尼科娃-德拉戈米尔

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

import { Test } from "./mod2"; //LINE X
declare global {
  interface Object {
    GetFooAsString(): string;
  }
}

Object.prototype.GetFooAsString = function () {
  return this.GetFoo().toString();
}

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章