【问题标题】:create-react-app typescript global.d.ts file doesn't workcreate-react-app typescript global.d.ts 文件不起作用
【发布时间】:2019-11-29 04:33:25
【问题描述】:

我在src 文件夹中有我的global.d.ts 文件,如下所示

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

【问题讨论】:

    标签: reactjs typescript create-react-app


    【解决方案1】:

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

    declare global {
      interface Window {
        config: {
          url: string;
        };
      }
    }
    
    // Adding this exports the declaration file which Typescript/CRA can now pickup:
    export {}
    

    【讨论】:

    • 非常好的零配置方法。
    【解决方案2】:

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

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

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

    更多关于这方面的信息可以在here找到。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-08
      • 2020-09-30
      • 2021-03-05
      • 2018-09-16
      • 2022-01-23
      • 1970-01-01
      • 2018-09-16
      • 2018-12-21
      相关资源
      最近更新 更多