create-react-app打字稿global.d.ts文件不起作用

时间:2019-07-20 13:07:30

标签: reactjs typescript create-react-app

我的global.d.ts文件在这样的src文件夹中

declare global {
  interface Window {
    config: {
      url: string;
    };
  }
}

然后在我组件的某个地方做

window.config = 'x';

ts显示此错误

Error:(10, 22) TS2339: Property 'config' does not exist on type 'Window'.

create-react-app用于此应用。

"react-scripts": "3.0.1",
"typescript": "3.5.3"

这就是tsconfig.json的样子

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve"
  },
  "include": [
    "src"
  ]
}

2 个答案:

答案 0 :(得分:6)

一种更简单的方法是从global.d.ts中导出一个空对象,如下所示:

declare global {
  interface Window {
    config: {
      url: string;
    };
  }
}

// Adding this exports the declaration file which Typescript/CRA can now pickup:
export {}

答案 1 :(得分:1)

如果您的.d.ts文件未导入或导出任何内容,则可以省略declare global块。

您需要确保此文件位于@types目录中,或者已将typeRoots配置为包括用于类型声明的目录,例如

{
  "compilerOptions": {
    "typeRoots": [
      "./node_modules/@types/",
      "./custom/path/to/declarations/"
    ]
  }
}

有关此内容的更多信息,请here