@types/gtag.js 错误:“config”类型的参数无法分配给“consent”类型的参数

Mar*_*son 7 google-analytics typescript typescript-typings

我正在尝试将 Google Analytics 添加到 Next.js 网站。我正在遵循JavaScript 中的指南,但我的应用程序是 TypeScript 安装 @types/gtag.js 后,我收到此错误:

No overload matches this call.
  The last overload gave the following error.
    Argument of type '"config"' is not assignable to parameter of type '"consent"'.ts(2769)
index.d.ts(19, 5): The last overload is declared here.
Run Code Online (Sandbox Code Playgroud)

在我的代码的这一行:

window.gtag('config', process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS, {
    page_path: url,
})
Run Code Online (Sandbox Code Playgroud)

以下是类型定义:https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/gtag.js/index.d.ts

我不确定类型是否不正确,但代码可能有效,因为它直接来自教程。

我的临时解决方法是声明gtag: any

declare global {
  interface Window {
    gtag: any
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 26

我收到此错误,并通过添加类型来修复此错误stringNEXT_PUBLIC_GOOGLE_ANALYTICS在您的情况下)。就我而言,因为类型process.env.NEXT_PUBLIC_GOOGLE_ANALYTICSstring | undefined.

  • window && window.gtag && window.gtag('config', process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS as string, { page_path: url, }); (3认同)