使用全局 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;
}
}
相關資源
- TypeScript error: Property 'X' does not exist on type 'Window'
- Augmentations for the global scope can only be directly nested in external modules or ambient module declarations(2669)
The text was updated successfully, but these errors were encountered: