【问题标题】:Why globally declared variable is not accessible via window in Deno TypeScript?为什么无法通过 Deno TypeScript 中的窗口访问全局声明的变量?
【发布时间】:2021-08-08 20:17:08
【问题描述】:

为什么下面示例中的context 不能作为window.context 访问?

它适用于get_context 函数但不适用于context 变量,为什么?

请注意它在 Deno TypeScript 设置中。

play

declare global {
  let context: number
  function get_context(): number
}

console.log(get_context())        // works
console.log(window.get_context()) // works
window.get_context = () => 1      // works

console.log(context)        // works
console.log(window.context) // Error
window.context = 2          // Error

export {}

【问题讨论】:

  • let 不会在 window 上创建属性。
  • @Ouroborus 哈哈,真的,谢谢,如果改成 var 就可以了!

标签: typescript deno


【解决方案1】:

由于context 不是块作用域,您需要使用var 而不是let 来声明它。如果您希望它只准备就绪,也可以使用const

Global Variables - Declaration Reference - TypeScript: Documentation:

使用declare var 声明变量。如果变量是只读的,您可以使用declare const。如果变量是块范围的,你也可以使用declarelet。

【讨论】:

    猜你喜欢
    • 2020-01-15
    • 1970-01-01
    • 2017-07-25
    • 2014-02-01
    • 2011-10-13
    • 2017-01-17
    • 2019-11-24
    • 2017-02-02
    • 2022-01-15
    相关资源
    最近更新 更多