为什么在 Deno TypeScript 中无法通过 window 访问全局声明的变量?

Why globally declared variable is not accessible via window in Deno TypeScript?

为什么下面示例中的 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 {}

由于 context 不是块范围的,您需要使用 var 而不是 let 来声明它。如果您希望它是只读的,您也可以使用 const

Global Variables - Declaration Reference - TypeScript: Documentation:

Use declare var to declare variables. If the variable is read-only, you can use declare const. You can also use declare let if the variable is block-scoped.