TypeScript 扩展全局 Window 时报错的解决


使用全局 window 上自定义的变更进,TypeScript 会报属性不存在,

console.log(window.foo) // ❌ Property ‘foo’ does not exist on type 'Window & typeof globalThis'.ts(2339)

需要将自定义变量扩展到全局 window 上,可通过在项目中添加类型文件或正常的 .ts 文件,只要在 tsconfig.json 配置范围内能找到即可。

types.d.ts

declare global {
  interface Window {
   	foo: string;
  }
}

此时再使用就正常了,

console.log(window.foo) // ✅

如果在进行类型扩展时报如下错误:

Augmentations for the global scope can only be directly nested in external modules or ambient module declarations.ts(2669)

可在类型文件中添加如下内容以指定文件为模板,报错消除。

+ export {};

declare global {
  interface Window {
    foo: string;
  }
}

相关资源

The text was updated successfully, but these errors were encountered:


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM