使用 google.maps 时出现打字稿错误 - 'google' 未定义

nis*_*ant 2 google-maps build typescript react-app-rewired

我在 package.json 中有以下内容

"@types/google.maps": "~3.48.3",
Run Code Online (Sandbox Code Playgroud)

// 在我的 tsx 文件中,顶部的第一行是

/// <reference types='google.maps' />
Run Code Online (Sandbox Code Playgroud)

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

980 号线是

onMarkerDragEnd = async (mapMouseEvent: google.maps.MapMouseEvent) => {
Run Code Online (Sandbox Code Playgroud)

//我也尝试过

/// <reference path='../../../../node_modules/@types/google.maps' />
Run Code Online (Sandbox Code Playgroud)

// 我也在 tsconfig.json 中尝试过

  "compilerOptions": {
    "types": [
      "google.maps"
    ]
  }
Run Code Online (Sandbox Code Playgroud)

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

react-app-rewired build
Run Code Online (Sandbox Code Playgroud)

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

Jus*_*elt 7

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

{
    "globals": {
        "google": "readonly"
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  devDependencies: {"@types/google.maps": ...}
Run Code Online (Sandbox Code Playgroud)

安装:

npm install -D @types/google.maps
Run Code Online (Sandbox Code Playgroud)

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

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