• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

I Like Kill Nerds

The blog of Australian Front End / Aurelia Javascript Developer & brewing aficionado Dwayne Charrington // Aurelia.io Core Team member.

  • Home
  • Aurelia 2
  • Aurelia 1
  • About
  • Aurelia 2 Consulting/Freelance Work

How to Extend the Window Object in TypeScript

TypeScript · September 29, 2022

In many cases when you’re working with TypeScript, there are type definitions available for almost every package out there.

However, in some circumstances, you might find yourself working with a third party that adds a property to the window object. Think a script tag like how Google Analytics works by adding in the ga property to the window.

It doesn’t matter if you are using Angular, React, Vue, Svelte, Aurelia, or any other framework or library, this approach works for all TypeScript projects.

Presumably, all of your source code is in a folder called src (it’s the most common place). You can name this file anything, but create a new file called index.d.ts and add in the following.

export {};

declare global {
  interface Window {
    globalProp: any;
  }
}

This will add type support for window.globalProp and stop TypeScript complaining about this property not existing. In the above example, we use “any" for situations where you just want it to work so, you can compile your code, but it’s better to properly type your defined properties where possible.

It’s rare that I need to add new properties to the window object, so this post is more a reference for myself and anyone else who can’t remember the right way to do this.

Dwayne

Leave a Reply Cancel reply

0 Comments
Inline Feedbacks
View all comments

Primary Sidebar

Popular

  • Testing Event Listeners In Jest (Without Using A Library)
  • How To Get The Hash of A File In Node.js
  • Thoughts on the Flipper Zero
  • Waiting for an Element to Exist With JavaScript
  • How To Paginate An Array In Javascript
  • How To Mock uuid In Jest
  • How To Get Last 4 Digits of A Credit Card Number in Javascript
  • How to Use Neural DSP Archetype Plugins With the Quad Cortex
  • How To Decompile And Compile Android APK's On A Mac Using Apktool
  • NBN Box Installed Inside of Garage, Where Do You Put The Modem?

Recent Comments

  • Kevmeister68 on Start-Ups and Companies That Embrace Work From Anywhere Will Be More Likely to Survive the Coming Recession in 2023
  • kevmeister68 on What Would Get People Back Into the Office?
  • Dwayne on PHP Will Not Die
  • Dwayne on How to Create a Blockchain With TypeScript
  • kevmeister68 on PHP Will Not Die

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz