I have an angular component where I would like to perform actions when a specific cookie is changed. I read that I can do it via CookieStore Api (https://developer.mozilla.org/en-US/docs/Web/API/CookieStore/change_event)
But when I try to use it in my angular component, the code does not compile:
ngOnInit() {
if ('cookieStore' in window) {
// Listen for changes to cookies
window.cookieStore.addEventListener('change', event => {
event.changed.forEach(change => {
console.log(`Cookie changed: ${change.name} = ${change.value}`);
});
});
} else {
console.log('Cookie Store API is not supported in this browser.');
}
}
Error is
TS2339: Property cookieStore does not exist on type Window & typeof globalThis
I am using angular version: 15.2.10. Is there any way I can use the CookieStore Api in my angular code? Either service or component?
2
Answers
You can resolve this by extending the Window interface to include cookieStore. Create a declaration file (e.g., window.d.ts) and add
This will let TypeScript recognize the API and compile correctly.
Stackblitz Demo
It’s not enough to define
Window.cookieStore
, you also need to define theCookieStore
type and the event listener overloadNow your
ngOnInit
will use the new types, and not throw any type errors