After upgrading my project to TypeScript 4.4.3 from 3.9.9, I encountered a change in the type declarations for the top
property.
My project utilizes
"strictNullChecks": true,
in its configuration file tsconfig.json
, and is browser-based rather than server-side on Node.js.
In TypeScript 4.4.3, the type declaration for top
now includes WindowProxy | null
(found in
node_modules/typescript/lib/lib.dom.d.ts
).
This modification results in an error1 whenever attempting to access properties of top
2: TS Playground
const topUrl = top.window.location.href; // => Object is possibly 'null'.
Is there a way to selectively disregard these errors specifically when top
could be null?3
1 The error serves as a precaution against situations where the website loads within an iframe, preventing access to top
due to cross-site scripting concerns. However, this is not applicable to my case since my 'X-Frame-Options'
is set to 'sameorigin'
, which restricts loading within cross-origin iframes.
2 Accessing properties of top
is essential because my project extensively employs iframes to load sub-pages under the same domain.
3 While there are potential workarounds to address the Object is possibly 'null'.
issue, implementing them across the large project would be cumbersome with minimal benefit.
let topUrl = top?.window.location.href || '';
let topUrl = '';
if (top) {
topUrl = top.window.location.href;
}
Ignoring these errors using // @ts-ignore
on every line involving top
is feasible but could lead to clutter and overlook other legitimate TypeScript errors on the same lines.
// @ts-ignore
const topUrl = top.window.location.href;