TypeScript 擴展全局 Window 時報錯的解決


使用全局 window 上自定義的屬性,TypeScript 會報屬性不存在,

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

需要將自定義變量擴展到全局 window 上,可通過在項目中添加類型文件或正常的 .ts 文件,只要在 tsconfig.json 配置范圍內能找到即可。

type.d.ts

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

如果在進行類型擴展時報如下錯誤:

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;
  }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM