How do you explicitly set a new property on `window` in TypeScript?
You need to extend the global Window
interface (usually in a .d.ts file or within a declare global
block) to tell TypeScript about the new property. For example:
declare global { interface Window { myCustomProperty: string; } } // Now you can assign: window.myCustomProperty = "Hello!";
This way, TypeScript recognizes window.myCustomProperty
as a valid property, rather than throwing an error.
1. Extend the Window
Interface
- Create or open a .d.ts file (e.g.,
global.d.ts
orwindow-extend.d.ts
) in your project. - Use a
declare global { ... }
block to re-declare theWindow
interface with your new property:
// global.d.ts declare global { interface Window { myCustomProperty: string; } }
- Now TypeScript knows that
window.myCustomProperty
exists and is a string.
Example Usage
window.myCustomProperty = "Some data"; console.log(window.myCustomProperty.toUpperCase()); // "SOME DATA"
TypeScript won’t complain about missing properties because your extended Window
interface includes myCustomProperty
.
2. Single-File Approach (Not Recommended for Larger Projects)
If you just need this in one file and you don’t want a separate .d.ts:
export {}; // Ensure this file is treated as a module. declare global { interface Window { myCustomProperty: string; } } // Now you can assign to window window.myCustomProperty = "Hello from single-file approach";
- The
export {}
ensures it’s recognized as a module rather than a script. - This approach works for small or demo projects, but a dedicated .d.ts file is cleaner for most real-world applications.
3. Using as any
as a Last Resort
You might see code like:
(window as any).myCustomProperty = "Hello!";
- This tricks TypeScript into ignoring type checks.
- It’s fine for quick hacks, but you lose all type safety around
myCustomProperty
. - The recommended approach is to properly extend the
Window
interface so you get type-checking.
4. When to Do This
- If you’re adding global variables or properties in the browser environment (e.g., for a library or framework plugin).
- If you want to store config data or a reference to an API object on
window
in a typed manner.
Often, it’s better to avoid polluting the global window
if possible. But if you do, an interface extension is the TypeScript-friendly approach.
Recommended Course
Summary
To explicitly set a new property on window
in TypeScript:
- Extend the global
Window
interface in a.d.ts
file (ordeclare global
block). - Define your custom property’s name and type.
- Assign to
window.propertyName
without complaints from the compiler.
This preserves type safety and ensures your code remains clear and maintainable.