首页 > 解决方案 > 声明全局更新窗口不起作用

问题描述

我有以下层次结构

/
  /definitions
     window.d.ts
  /components
  ...
  tsconfig.json

以我window.d.ts的存在

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"
  ]
}

当我运行 dev-server 时,我得到

[at-loader] Using typescript@2.6.1 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文件工作正常...

标签: javascripttypescript

解决方案


在这里找到了这个答案:

declare global {
    interface Window { otherKey: any; }
}

window.otherKey= window.otherKey|| {};

推荐阅读