javascript - การประกาศตัวแปรระดับโลกเพื่ออัปเดต Window ไม่ทำงาน
ฉันมีลำดับชั้นดังต่อไปนี้
/
/definitions
window.d.ts
/components
...
tsconfig.json
ด้วย window.d.ts ของฉัน being
export {}
declare global {
interface Window { otherKey: any; }
}
และ tsconfig.json ของฉันกำลัง
{
"compilerOptions": {
"outDir": "./dist",
"allowJs": true,
"target": "es5",
"lib": ["es5", "es6"],
"jsx": "react",
"sourceMap": true,
"module": "es6",
"preserveConstEnums": true,
"removeComments": true,
"noImplicitAny": false,
"moduleResolution": "node",
"noUnusedParameters": false,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"baseUrl": ".",
"paths": {
"window": ["definitions/window.d.ts"]
}
},
"include": [
"./App.tsx"
]
}
เมื่อฉันรันเซิร์ฟเวอร์พัฒนา ฉันได้รับ
[at-loader] Using [email from typescript and "tsconfig.json" from /correct/path/tp/tsconfig.json.
แต่เมื่อ webpack เสร็จสิ้น ฉันได้รับ
ERROR in [at-loader] ./component/SomeApp.tsx:78:35
TS2339: Property 'otherKey' does not exist on type 'Window'.
ฉันเพียงแค่ใช้ window.otherKey โดยไม่ต้องมี declare var window: any อื่น ๆ หวังว่า otherKey จะมีอยู่จริง
ทำไมสิ่งนี้ถึงใช้ไม่ได้?
แก้ไข
ฉันสังเกตเห็นว่าสิ่งนี้เกิดขึ้นเพียงกับไฟล์ .tsx เท่านั้น ไฟล์ .ts ใช้งานได้ปกติ ...
คำตอบ #1
พบคำตอบนี้ที่นี่:
declare global {
interface Window { otherKey: any; }
}
window.otherKey= window.otherKey|| {};
