iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🤫
The Quickest and Dirtiest Way to Add Objects to the window Object in TypeScript
TL;DR
You can do this in a very quick and dirty way,
but I cannot take any responsibility if you get scolded for using this in production (obviously, right?)
(window as any).myString = "it works"; // It goes in
const myString = (window as any).myString as string; // You can retrieve it
I just wanted to add an object directly under window
Usually, I'm all like "Static typing is the beeeeesssst!!!!"
and yet I struggled so much just to do something that was possible in JavaScript years ago...
If you want to do it properly, you should prepare a definition file (like window.d.ts) and extend the window object through Interface merging.
- References
- Merging Interfaces - TypeScript Document
- Extending window and defining global variables in TypeScript - Developers.IO
However, I just wanted to do it simply for a quick experiment...
In JavaScript, it looks like this.
window.myString = "Goes in easily"; // It works
const myString = window.myString; // You can retrieve it if it exists
Once you figure it out, it's just a matter of "of course you can do that even with the window object."
I referred to this:
Addendum
Doing it properly might work with this method:
- Let's get friendly with TypeScript type definition files | Hatena Developer Blog
Discussion