The window Object in TypeScript
This article explains the window object in TypeScript.
You can learn about the properties and methods of the window
object through code.
YouTube Video
The window Object in TypeScript
window
is a global object in TypeScript and JavaScript representing the entire browser window. It includes many properties and methods to access browser APIs, manipulate the DOM (Document Object Model), use timers, storage, and other features.
tsconfig.json and the window
Object
In TypeScript, when accessing the window
object, the browser-specific global features have type definitions, enabling editor autocompletion and type checking. Thanks to TypeScript's standard type definition file (lib.dom.d.ts
), TypeScript recognizes various properties and methods of the window
object.
When using TypeScript, it is common to place a tsconfig.json
file at the root of the project. This file is used to specify compiler options and the scope of type definition files.
When working with window
, it is especially important to enable browser type definitions (DOM type definitions). Without this, window
and document
will result in type errors.
1{
2 "compilerOptions": {
3 "target": "es6",
4 "module": "esnext",
5 "strict": true,
6 "lib": ["es6", "dom"], // Enable DOM type definitions
7 "outDir": "./dist"
8 },
9 "include": ["src"]
10}
- By specifying
"lib": ["es6", "dom"]
, the types ofwindow
anddocument
will be correctly recognized and auto-completed.
Main window
Properties and Methods
window.document
window.document
is a property used to access the DOM of the page. You can retrieve elements and make changes to the DOM.
1console.log(window.document.title); // Display the title of the current document
- In this example, the current document's title is displayed.
window.localStorage
/window.sessionStorage
window.localStorage
andwindow.sessionStorage
are properties used to access storage features that allow saving user data in the browser.
1window.localStorage.setItem('key', 'value'); // Save data
2const value = window.localStorage.getItem('key'); // Retrieve data
3console.log(value); // 'value'
- In this example, data is saved to
localStorage
, then retrieved and displayed.
window.location
window.location
is an object used to retrieve and manipulate information about the current URL. You can perform redirects and change URLs.
1console.log(window.location.href); // Display the current URL
2window.location.href = 'https://example.com'; // Redirect to another page
- In this example, the URL is displayed and the user is redirected to another page.
window.setTimeout
/window.setInterval
window.setTimeout
andwindow.setInterval
are methods used to run functions after a delay or at regular intervals.
1window.setTimeout(() => {
2 console.log('This will be executed after 2 seconds');
3}, 2000);
- This code executes a process that outputs a message to the console after two seconds.
window.alert
/window.confirm
/window.prompt
alert
,confirm
, andprompt
display dialog boxes to show alerts or request input from the user.
1window.alert('Alert message');
- This code displays an alert dialog to notify a message.
Events of the window
Object
Since window
is part of the DOM, you can also listen to events directly. In TypeScript, types are auto-completed, so using incorrect event names or properties will cause errors.
Window Resize Event
1window.addEventListener("resize", (event) => {
2 console.log("Window resized:", window.innerWidth, window.innerHeight);
3});
- This code outputs the new width and height to the console when the window size changes.
Keyboard Event
1window.addEventListener("keydown", (event: KeyboardEvent) => {
2 console.log(`Key pressed: ${event.key}`);
3});
- This code outputs the pressed key to the console when the user presses a key.
Page Load Event
1window.addEventListener("load", () => {
2 console.log("Page fully loaded");
3});
- This code outputs a message to the console when the page has finished loading.
Notes
-
In TypeScript, event object types are inferred, so being mindful of types like
KeyboardEvent
orMouseEvent
makes your code safer. -
It is recommended to remove event listeners when they are no longer needed. You can remove listeners using the
window.removeEventListener
method.
1function handleClick() {
2 console.log("Clicked!");
3}
4
5// Add event listener
6window.addEventListener("click", handleClick);
7
8// Remove event listener
9window.removeEventListener("click", handleClick);
- This code shows an example of adding and then removing a listener for a click event.
When Adding Custom Properties
When adding custom properties to the window
object, type extension is necessary in TypeScript to avoid type errors.
1// Add a custom property to the window
2interface Window {
3 myCustomProperty: string;
4}
5
6window.myCustomProperty = "Hello, World!";
7console.log(window.myCustomProperty); // "Hello, World!"
- This code is an example of adding a custom property to the
window
object in TypeScript, setting a value, and displaying it.
Cautions When Using the Global window
Object
Due to TypeScript's strict type checking, attempting to use non-existent properties or methods will result in errors. For example, attempting to access a non-existent property on the window
object as is will cause an error, so you need to properly extend the type.
As such, the window
object plays a central role in accessing various features of browser applications, and in TypeScript, you can use it safely by leveraging type checking.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.