Typescript this is window

Extend Window type with Typescript

During typescript app development, sometime you need to access properties or functions of the Window object. Some of these properties or functions are not available in the window object defined by the browser. Those may be defined by Third-party libraries you can add to your pages like Google Tag Manager for example. Because of this, you need to extend the Window type with the properties or functions you need to access.

TypeScript Window type

The Window type is defined in the lib.dom typescript module. You can find the definition of the Window type at the following TSDoc.

When can you have new properties not defined by your code in the Window object? An example is when you want to add Google Tag Manager or Google Analytics to your page. Those scripts are not loaded by your code directly but you may communicate with them through some window object properties. For Google Tag Manager, the datalayer property is added and some of the functions are also added.

In this case, you will have the following error:

Property does not exist on type 'window & typeof globalthis' 

Extend Window type with the missing properties

In order to extend the Window type, you need to add the missing properties or functions.

The following code snippet will extend the Window type with the missing properties or functions.

declare global   interface Window   gtag: (. args: any[]) => void  dataLayer: Recordstring, any>  > > 

Do not forget to add the file containing this snippet to the list of project files for the Typescript compilation.

For example, in a NextJS project, you can add the snippet in the globals.d.ts file like this:

interface Window   gtag: (. args: any[]) => void  dataLayer: Recordstring, any> > 

Hope this article helps you to avoid this Typescript error.

If you’re seeking solutions to a problem or need expert advice, I’m here to help! Don’t hesitate to book a call with me for a consulting session. Let’s discuss your situation and find the best solution together.

Источник

How to Properly Type Window

Matt Pocock

In pretty much any frontend application, you’ll likely have encountered this error:

Property ‘X’ does not exist on type ‘Window & typeof globalThis’.

ts
window.X;
Property 'X' does not exist on type 'Window & typeof globalThis'.2339Property 'X' does not exist on type 'Window & typeof globalThis'.

In this article, we’ll lay out several different solutions to this issue.

Quick Fix

The Window interface is defined globally in a file called lib.dom.d.ts . You can change it using various techniques:

  • To change it globally within a .ts or .tsx file, you can use declare global and interface Window :
ts
declare global
interface Window
X: number;
>
>
window.X;
(property) Window.X: number
ts
interface Window
X: number;
>
ts
declare const window:
X: number;
> & Window;
window.X;
(property) X: number

Explanation

The interface Window lives in the global scope in TypeScript. It ships as part of the DOM types in lib.dom.d.ts , which describes what methods are available in the browser.

The issue comes up when a third-party script (or perhaps our own code) adds something to the window:

This is a problem because TypeScript doesn’t know about the X property, and so it throws an error when you try to access it:

ts
window.X;
Property 'X' does not exist on type 'Window & typeof globalThis'.2339Property 'X' does not exist on type 'Window & typeof globalThis'.

So, we need to somehow change the global definition of Window to include the new property that TypeScript doesn’t know about.

Solution 1: declare global in a .ts or .tsx file

The first solution is to use declare global to change the global definition of Window :

ts
declare global
interface Window
X: number;
>
>
window.X;
(property) Window.X: number

This works for two reasons. First, declare global tells TypeScript that anything inside it should be added to the global scope.

Second, we take advantage of declaration merging. This is a rule in TypeScript where interfaces with the same name in the same scope get merged. So by redeclaring Window in the same scope, we can append new properties to it.

This wouldn’t work if we used type because types don’t support declaration merging.

ts
declare global
type Window =
Duplicate identifier 'Window'.2300Duplicate identifier 'Window'.
X: number;
>;
>

This solution only works inside a .ts or .tsx file because declare global only works inside a module. So this solution is a little awkward in terms of where you place the definition in your project. In its own module? Colocated with something else?

Solution 2: A .d.ts file

A neater solution is to use interface Window in a .d.ts file:

ts
// window.d.ts (choose any filename you like)
interface Window
X: number;
>
ts
// your-app.ts
window.X;
(property) Window.X: number

This works because anything you place in a .d.ts automatically goes into the global scope, so there’s no need for declare global .

It also lets you place the global definition in a single file, on its own, which feels a little cleaner than trying to figure out which .ts file to put it in.

Solution 3: Single-module override

If you’re concerned about adding types into the global scope, you can use declare const window to override the type of window in a single module:

ts
declare const window:
X: number;
> & Window;
window.X;
(property) X: number

declare const window acts like const window , but on the type level. So it only acts on the current scope — in this case, the module. We declare the type as the current Window , plus the new property X .

This solution gets a little annoying if you need to access window.X in multiple files because you’ll need to add the declare const window line to each file.

Which solution should I use?

Personally, I tend to reach for solution 2 — a .d.ts file. It’s the fewest lines of code and the easiest to place in your project.

I don’t mind adding types into the global scope. By actually changing the type of Window , you’re more accurately describing the environment your code executes in. In my book, that’s a bonus.

But if you’re really concerned about it, use the declare const solution.

Share this article with your friends

Why You Can’t Use Dot Notation On Types

In TypeScript, dot notation cannot be used to access type properties, but indexed access types provide more flexibility and are already available.

Strongly Type useRef with ElementRef

Using useRef with native elements in React can be confusing, but ElementRef provides an easier solution by extracting the element type.

Explained: Cannot use JSX unless the ‘—jsx’ flag is provided

Learn how to fix the «Cannot use JSX unless the —jsx flag is provided» error in TypeScript by updating your tsconfig.json file.

There Is No Such Thing As A Generic

Understanding generics can be challenging because the term is overloaded. Instead, use the terms «type arguments» and «type parameters» for clarity.

TypeScript Generics in 3 Easy Patterns

What you think of as «generics» in TypeScript are actually three different patterns.

How to Iterate Over Object Keys in TypeScript

Iterating over object keys in TypeScript can be challenging. One option is casting to keyof typeof to access values, or using type predicates.

Источник

TypeScript Extend Window

TypeScript Extend Window

  1. TypeScript Window Object
  2. Declare New Property in the Window Object in TypeScript
  3. Interface Declaration Merging in TypeScript

This article shows how to extend a TypeScript window .

TypeScript Window Object

A window is a built-in object defined in the browser. It is the window object that contains a DOM document.

You might need to access the properties and functions associated with the browser window object. The built-in window object carries a lot of useful properties and functions out of the box.

Some of the frequently used window object properties and functions are listed in the following.

  1. Properties: EventTarget , document , console , event , localStorage , onLoad , etc.
  2. Methods: addEventListener , fetch , alert , atob , btoa , open , prompt , print , etc.

Usually, TypeScript defines its types in different modules. Hence, the window type is defined in the lib.dom module.

In some scenarios, the built-in methods and properties are not enough. Whenever your TypeScript project uses Google Analytics or Tag Manager libraries, these scripts might not be loaded by your code.

Hence, we need a way to communicate with those third-party tools via the window object properties and methods.

Declare New Property in the Window Object in TypeScript

In JavaScript, it is quite straightforward to declare a new property or method in the built-in window object. We can use the following ways to define a new property in the window object with JavaScript.

window.myProp = 'newly declared property'; window['myProp'] = 'newly declared property'; 

Let’s inspect the window object in the browser console.

declare a new property in javascript

In TypeScript, the above approaches wouldn’t work. If we try to declare a new property in the window object like in JavaScript, TypeScript will throw an error, as shown in the following.

window.anotherNewProp = 'this is a property on window object in typescript'; 

declare a new property in typescript

Usually, a TypeScript object type is based on a class or an interface. Let’s say we have a class called Animal , as shown in the following.

class Animal   name: string;  color: string; > 

Let’s create an Animal object and assign some values to the name and color properties.

class Animal   name: string;  color: string; >  let newAnimal = new Animal();  newAnimal.name = 'lion'; newAnimal.color = 'grey'; 

The above code will compile without any issue.

Next, we will try to declare a new property numberOfLegs on the same Animal object and assign a value.

class Animal   name: string;  color: string; >  let newAnimal = new Animal();  newAnimal.name = 'lion'; newAnimal.color = 'grey'; newAnimal.numberOfLegs = 4; 

error declare a new property on object

It raises an error. We can’t declare new object properties like that in TypeScript.

To resolve that, we first need to add the numberOfLegs property to the Animal class.

This is the same issue with the built-in window object also. The main concern is TypeScript window object is not created by ourselves.

It comes with a browser. Hence we need a proper way to add a property to this built-in object.

Interface Declaration Merging in TypeScript

TypeScript supports the declaration merging technique out of the box. The simplest type of declaration merging is interface merging.

Whenever the multiple interfaces are declared with the same name, TypeScript will merge all the interfaces declarations into one.

The built-in window object is based on the TypeScript window interface. Hence, we can use the TypeScript interface merging technique to add a new property to the built-in interface.

Let’s create a new interface named window .

interface Window   myProp: string; > 

Next, we will try to access the myProp property in the window object.

interface Window   myProp: string; >  window.myProp = 'typescript window object property'; 

Interface Declaration Merging in TypeScript

There are no issues raised by the TypeScript compiler this time. Defining new properties or methods in the window object is recommended if you consider the types.

If there are no concerns on types, the following syntax can be used to declare new properties on the window object.

(any>.window).myProp = 'typescript property on window object'; 

You can declare functions as well.

(any>.window).NewFunction = () =>   console.log('new function on window object'); > 

Both techniques can be used with TypeScript to add new properties or methods to the window object. The choice is yours based on the context.

Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.

Источник

Читайте также:  Php array functions explode
Оцените статью