【问题标题】:typescript error using google.maps - 'google' is not defined使用 google.maps 的打字稿错误 - 未定义 \'google\'
【发布时间】:2023-02-09 09:34:16
【问题描述】:

我在 package.json 中有以下内容

"@types/google.maps": "~3.48.3",

// in my tsx file the first line at the top is

/// <reference types='google.maps' />

但是在访问 google.maps.MapMouseEvent 时 - 我收到错误“google”未定义。 第 980:43 行:'google' 未定义 no-undef

980行是

onMarkerDragEnd = async (mapMouseEvent: google.maps.MapMouseEvent) => {

// I also tried

/// <reference path='../../../../node_modules/@types/google.maps' />

// I also tried in tsconfig.json

  "compilerOptions": {
    "types": [
      "google.maps"
    ]
  }

但错误仍然存​​在。我正在使用编译打字稿

react-app-rewired build

寻找有关如何在打字稿中使用 @types/google.maps 的任何提示。

【问题讨论】:

    标签: typescript google-maps build react-app-rewired


    【解决方案1】:

    no-undef 实际上是一个 eslint 错误,可以用 https://eslint.org/docs/user-guide/configuring/language-options#specifying-globals 修复

    {
        "globals": {
            "google": "readonly"
        }
    }
    

    使用最新版本的打字稿,除了 package.json 中的以下内容外,您不需要任何其他内容。

      devDependencies: {"@types/google.maps": ...}
    

    安装:

    npm install -D @types/google.maps
    

    没有三重斜杠引用,没有导入,没有 compilerOptions.types。

    有关示例,请参见https://codesandbox.io/embed/github/googlemaps/js-samples/tree/sample-marker-simple

    【讨论】:

    • 谢谢!如果正在使用 typescript,继续使用 eslint 是否有任何价值?
    • 需要在两者中指定 google,因为它们不重叠。
    • 通过运行“yarn add @types/google.maps”解决这个问题。
    猜你喜欢
    • 2017-12-22
    • 2018-04-20
    • 2021-02-14
    • 2018-06-05
    • 2022-10-06
    • 2022-09-27
    • 2019-05-01
    • 1970-01-01
    • 2018-01-05
    相关资源
    最近更新 更多