【问题标题】:How do you explicitly set a new property on `global` in TypeScript?你如何在 TypeScript 中显式地设置 `global` 的新属性?
【发布时间】:2020-07-02 02:29:54
【问题描述】:

我有一个这样定义的变量:

(global as any).State = {
  variables: {},
};

我的问题是,如何声明State 的类型签名?如果我说(global as any).State: Something = ...,编译器会给我一个错误,说; expected。

据我所知,这与这个问题相同,但它与window 变量有关,而不是global 变量:How do you explicitly set a new property on `window` in TypeScript?

【问题讨论】:

  • 我认为,; expected 与JS ASI 有很大关系。尝试在上面的代码 sn-p 之前插入分号,它也应该可以工作(尽管没有强类型)。

标签: node.js typescript


【解决方案1】:

global 是 window 的 Node.JS 等价物和包含在 @types/node 中的全局变量声明:

// @types/node/globals.d.ts
declare var global: NodeJS.Global;
从模块文件中扩充global:
export {}

declare global { // declare global is TS specific, it is not the Node global!
  namespace NodeJS {
    interface Global {
      State: {
        variables: {}
      }
    }
  }
}
从脚本文件内部扩充global(没有export/import):
declare namespace NodeJS {
  interface Global {
    State: {
      variables: {}
    }
  }
}

然后您将能够设置State 而无需依赖any:

global.State = { variables: {} }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    • 2017-04-06
    • 2021-04-09
    相关资源
    最近更新 更多