How To Add Custom Types to the Window With TypeScript | by Jesse Langford | May, 2022

A quick information to creating the proper setting

By olllinka2

A couple of weeks in the past, I used to be tasked with integrating a third-party module with considered one of our purposes. It was an software that wanted to be loaded by way of a script tag in our HTML, much like how you’d load Google analytics. As soon as the web page masses and the scripts are fetched, we are able to see a brand new property on the window object.

This object has callable strategies wanted to attach with the service. We are able to simply name these strategies on the window inside a JavaScript software. Issues get a bit trickier within a TypeScript mission.

On this article, I’ll be going over the right way to add Window sorts to your software and the right way to increase the Window to incorporate customized properties.

The very first thing to do is so as to add base Window sorts. Including the window object to your mission is feasible by including “DOM” to your tsconfig lib array.

"lib": ["DOM"]

You may learn extra in regards to the sorts you get from together with that possibility here. With that in place, you’ll have entry to what’s out there on the Window object.

With Window sorts in place, the following factor to do is add a customized sort to the Window object that our IDE will decide up.

Create a brand new file in your mission referred to as globals.d.ts. I selected to place this below a folder referred to as sorts in my src folder. Right here’s the code:

The above assertion will increase the present Window object with the profitwell perform.

The export is required for TypeScript to categorise this file as an exterior module.

In my case, the thing I used to be extending was a perform. You’ll have to learn any documentation out there in case you are mocking a third-party service to verify your sorts match.

With the file in place, the very last thing to do is import the file on the topmost degree of your software so TypeScript can decide it up. I used to be utilizing React, so I added this line to my rootindex.tsx file.

import "./sorts/globals"

Restart your IDE, and you need to have entry to your new sort on the Window object.

Now you need to have all of the instruments in place to enhance the Window object nevertheless you select.

Thanks for studying.

Keep tuned for extra!

More Posts