create-react-app打字稿global.d.ts文件不起作用 [英] create-react-app typescript global.d.ts file doesn't work

查看:1273
本文介绍了create-react-app打字稿global.d.ts文件不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got my global.d.ts file in src folder like this

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用于此应用。

create-react-app is used for this 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"
  ]
}


推荐答案

提供了您的 .d.ts 文件未导入或未过期没什么,您可以省略 declare global 块。

Provided your .d.ts file doesn't import or export anything, you can omit the declare global block.

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

You will need to make sure this file is either in an @types directory, or that you have configured your typeRoots to include the directory for your type declarations e.g.

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

有关此的更多信息,请参见此处

Some more info about this can be found here.

这篇关于create-react-app打字稿global.d.ts文件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆