Borislav Hadzhiev
Wed Mar 02 2022·2 min read
Photo by Lê Tân
To extend the window type in TypeScript, create a .d.ts
file where you
extend the Window
interface adding the names and types of the properties you
intend to access on the window
object. TypeScript looks for .d.ts
files in
the same places it looks for your regular .ts
files.
In your src
directory, create a types
directory that contains the following
index.d.ts
file:
export {}; declare global { interface Window { myProperty: string; } }
The example above shows how to extend the Window
interface with a property
named myProperty
that has a type of string
.
You need to add the names and types of all of the properties you intend to
access on the window
object.
For example, if you don't know the type of the specific property and want to
turn off type checking, set it to any
.
export {}; declare global { interface Window { myProperty: any; } }
Now, I'm able to set and access the specified property on the window
object
without getting any errors.
// ✅ OK window.myProperty = 'hello world'; console.log(window.myProperty);
If you try to access a property that you haven't added to the extended Window
interface and does not exist on the original Window
interface, you'd get an
error:
// ⛔️ Property 'example' does not exist on // type 'Window & typeof globalThis'.ts(2339) window.example = 'hello';
If you are getting an error in your IDE, try adding the path to your types
directory to your tsconfig.json
file.
{ "compilerOptions": { // ... rest "typeRoots": ["./node_modules/@types", "./src/types"] } }
We used the export {}
line in our index.d.ts
file to mark it as an external
module. A module is a file that contains at least 1 import
or export
statement. We are required to do that to be able to augment the global scope.
index.d.ts
file according to your use case.You should add the names (and types) of all of the properties you intend to
access on the window
object.
export {}; declare global { interface Window { myProperty: any; } }
The provided file simply adds a myProperty
property with a type of any
,
which is most likely not what you need.
TypeScript looks for .d.ts
files in the same places it looks for your regular
.ts
files, which is determined by the include
and exclude
settings in your
tsconfig.json
file.
TypeScript will merge the declared from you Window
interface with the original
Window
interface, so when you use the window
object, you will be able to
access properties from both interfaces.