0

so I am trying to implement google analytics in my svelte-kit app. For that I need to insert a little script in the +layout.svelte file. As friends recommended me to switch from JS to TS I try to do it in TS, but I am still very noob. enter image description here

So I declared this interface with the same name as the "window" object, which according to the ts-handbook is called an alias and should be picked up automatically, but it is not as you can see - my linter is screaming at me that "Property 'dataLayer' does not exist on type 'Window & typeof globalThis'.ts(2339)" enter image description here

I really appreciate your help in this matter in order to fix this. Thank you!

CondorW
  • 167
  • 10

1 Answers1

0

You can only extend types you already imported, and window is an ambient type, so you cannot change or import it. You can re-declare window like this:

Playground Link
interface GAWindow {
  dataLayer: Record<string, any>[];
}
let w = window as (GAWindow & typeof window)
if (w.dataLayer) {}

(Note: This is the case because extending window is not really type-safe, so TS has no native support for it because it is inherently unsafe, so you have to explicitly use another variable. You can also declare global, but then the change is global, which you might want to avoid.)

lxhom
  • 650
  • 4
  • 15
  • So is the solution you proposed best practice - or what would be the best practice to do in this case? Because according to the duplicate Answers answerer I only have this problem because of a top-level import (in this case I import 2 svelte components) which I can hardly avoid. So how would I go about it in the "proper" way? – CondorW Mar 18 '23 at 16:29