使用全局 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: |
TypeScript 擴充全局 Window 時報錯的解決 CC BY-NC-SA 署名-非商業性使用-相同方式共享