Useful Snippets

Welcome!


This blog is used to collect useful snippets related to Linux, PHP, MySQL and more. Feel free to post comments with improvements or questions!

RSS Latest posts from my personal blog


Most viewed posts


Subscribe to RSS feed


Extending window and document global objects in TypeScript

Stanislav KhromovStanislav Khromov

Sometimes you will run into cases where a library or other code adds things to the global window or document objects and TypeScript will complain if it’s not aware of these properties. This will lead to a dreaded “property does not exist” error from the TypeScript compiler. To fix this you can type them yourself easily!

Let’s say that we have a window.clicks property that is a number, we can type it like this:

interface Window {
  clicks: number;
}

Or let’s say we have a document.items which is an array of strings, we can type it like this:

interface Document {
  items: string[];
}

Now you can happily use them in your code without TypeScript complaining:

console.log(window.clicks);
console.log(document.items);

Further reading

Web Developer at Aftonbladet (Schibsted Media Group)
Any opinions on this blog are my own and do not reflect the views of my employer.
LinkedIn
Twitter
WordPress.org Profile
Visit my other blog

Comments 0
There are currently no comments.