【问题标题】:How to specify global type declarations in create-react-app?如何在 create-react-app 中指定全局类型声明?
【发布时间】:2021-08-23 19:16:00
【问题描述】:

我在我的 create-react-app 项目中设置全局类型时遇到问题。 这是我的 tsconfig.json 文件。

{
    "compilerOptions": {
        "baseUrl": "./",
        "paths": {
            "components/*": [
                "src/app/components/*"
            ],
            "constants/*": [
                "src/app/constants/*"
            ],
            "services/*": [
                "src/app/services/*"
            ],
            "reducers/*": [
                "src/app/reducers/*"
            ],
            "selectors/*": [
                "src/app/selectors/*"
            ],
            "types/*": [
                "src/app/types/*"
            ],
            "pages/*": [
                "src/app/pages/*"
            ],
            "styles/*": [
                "src/static/styles/*"
            ],
        },
        "target": "es5",
        "lib": [
            "dom",
            "dom.iterable",
            "esnext"
        ],
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "noImplicitAny": false,
        "forceConsistentCasingInFileNames": true,
        "noFallthroughCasesInSwitch": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": true,
        "jsx": "react-jsx",
        "typeRoots": ["node_modules", "typings"],
    },
    "include": [
        "src"
    ],
    "exclude": ["node_modules", "**/*.js"]
}

如您所见,我在项目的根目录下创建了一个 typings 文件夹,我将在其中保存全局类型和其他一些类型。 所以在我的打字文件夹中,我有一个包含此声明的 global.d.ts 文件。

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

但在我的反应组件中,我有这个打字稿错误

类型'Window & typeof 上不存在属性'fastlink' globalThis'。

我已经在这里调查了很多文章和帖子,也阅读了文档,但没有结果。

【问题讨论】:

  • 不确定您是否有同样的问题,但也许这个answer 会有所帮助

标签: javascript reactjs typescript types create-react-app


【解决方案1】:
interface Window { 
  fastlink: any;
}

无需声明全局,直接在界面Window中定义即可。

你可以通过window.fastlink访问它

小心使用全局变量。

【讨论】:

    猜你喜欢
    • 2019-04-02
    • 2022-01-17
    • 2019-03-08
    • 2019-01-19
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    相关资源
    最近更新 更多