使用全局 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;
}
}