Sling Academy
Home/TypeScript/TypeScript and Window Object: A Complete Guide

TypeScript and Window Object: A Complete Guide

Last updated: January 07, 2024

Introduction

When the worlds of TypeScript’s type safety collide with the global expanse of the Window object, a labyrinth of possibilities unfolds for developers. This guide unfurls this sail, navigating through the TypeScript-tinted waters of Window object manipulation.

Understanding the Window Object

The Window object is a global object representing the window in which the script is running. Here’s your first example of accessing a property on the Window object:

console.log(window.location.href); // Outputs current URL

TypeScript, being a superset of JavaScript, inherits these characteristics but adds the twist of types. Observe:

const currentUrl: string = window.location.href;
console.log(currentUrl); // Type is explicitly set as string

With TypeScript, declaring the type is optional if it can be inferred, but recommended for better clarity.

Modifying Window Properties

In TypeScript, modify the Window object carefully, as type checking won’t like it if you do something unexpected:

interface Window {
  appVersion: string;
}

// Extend the window
window.appVersion = '1.0.0';

console.log(window.appVersion); // Outputs '1.0.0'

Using Window Methods

Let ‘s dive into Window methods:

window.alert('Welcome to TypeScript!'); // It 's still JavaScript at heart

When adding a method or not known by TypeScript, an ‘expanding the existing type with a declaration merging’ becomes necessary:

interface Window {
  fancyAlert: (msg: string) => void;
}

window.fancyAlert = (msg) => alert(`Fancy: ${msg}`);
window.fancyAlert('Hi there!');

Working with Window Events in TypeScript

TypeScript ‘s static types shine with event management:

window.addEventListener('resize', (event: UIEvent) => {
  console.log('Resized to: ', event.target.innerWidth);
});

Notice how we explicitly define ‘event’ as type ‘UIEvent’, narrowing down the multitude of possible types it could be.

Using TypeScript Enums and the Window Object

Enums are a useful feature in TypeScript. Utilizing enums for Window property values keeps our code organized:

enum FileType {
  PDF = 'application/pdf',
  Text = 'text/plain',
  JPEG = 'image/jpeg'
}

window.localStorage.setItem('preferredFileType', FileType.PDF);

Here, the type safety of enums ensures that only allowed values are used.

Handling Global Variables

Finally, the following example shows managing global variables within the window object:

(window).globalVar = 'This is global!';
console.log((window).globalVar); // Output: This is global!

In TypeScript, casting window to ‘any’ bypasses type safety, thus this should be used sparingly and carefully.

Advanced Patterns

Advanced usage comes into the scene with Generic Types for window custom properties and methods:

function decorateWindow<T>(key: string, value: T): void {
  ((window))[key] = value;
}

interface CustomWindowMethods {
  fancyLog: (msg: string) => void;
}

decorateWindow('fancyLog', (msg) => console.log('Fancy Log:', msg));
window.fancyLog('Window decoration is neat!');

Here, a Generic Type extends window functionality in a type-safe fashion.

Conclusion

Grasping the interweaving of TypeScript’s type discipline with the Window object’s expansiveness affords developers strength through understanding. Now, gentle reader, with newfound acumen in TypeScript and Window object mastery, go forth and craft mighty applications without the silent forbearance of runtime surprises!

Next Article: TypeScript and Form Handling: A Complete Guide

Previous Article: TypeScript and DOM Manipulation: A Complete Guide

Series: The First Steps to TypeScript

TypeScript

You May Also Like

  • TypeScript: setInterval() and clearInterval() methods (3 examples)
  • TypeScript sessionStorage: CRUD example
  • Using setTimeout() method with TypeScript (practical examples)
  • Working with window.navigator object in TypeScript
  • TypeScript: Scrolling to a specific location
  • How to resize the current window in TypeScript
  • TypeScript: Checking if an element is a descendant of another element
  • TypeScript: Get the first/last child node of an element
  • TypeScript window.getComputerStyle() method (with examples)
  • Using element.classList.toggle() method in TypeScript (with examples)
  • TypeScript element.classList.remove() method (with examples)
  • TypeScript: Adding Multiple Classes to An Element
  • element.insertAdjacentHTML() method in TypeScript
  • TypeScript – element.innerHTML and element.textContent
  • Using element.removeAttribute() method in TypeScript
  • Working with Document.createElement() in TypeScript
  • Using getElementById() method in TypeScript
  • Using Window prompt() method with TypeScript
  • TypeScript – window.performance.measure() method (with examples)