If you are using an integrated development environment (IDE), you may notice a red squiggly line highlighting the problematic part of your expression:
window.open(externalUrl, '_blank').focus(); // issue
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//Object is possibly 'null'
The error message indicates that
window.open(externalUrl, '_blank')
could potentially be
null
, not necessarily the entire
window
object. Therefore, in addressing this particular error, you do not need to check if
window
itself is null, assuming there is one available in your JavaScript runtime environment.
This error aligns with the information provided in the MDN documentation for Window.open()
, stating that a return value of null
signifies an inability to open the window. To tackle this issue, you should examine the return value and only invoke focus()
if it is not null. Attempting to do so differently like below will still trigger an error:
if (window.open(externalUrl, '_blank')) {
window.open(externalUrl, '_blank').focus(); // still error
}
The compiler does not assume that a successful first call to window.open()
guarantees success for subsequent calls. While it might seem improbable that the second call would fail when the first one doesn't, there is no certainty. Additionally, opening two windows simultaneously may not align with your intentions.
So, how can we handle this situation correctly? The solution that works well with most TypeScript versions involves storing the result in a variable and then verifying it:
const w = window.open(externalUrl, '_blank');
if (w) {
w.focus(); // now okay
}
For TypeScript 3.7 and later, you have access to the optional chaining operator, ?.
. This allows you to express the above logic more succinctly as follows:
window.open(externalUrl, '_blank')?.focus(); // also works
In due time, the optional chaining operator is expected to become a part of JavaScript itself. Until then, the code is transpiled into JavaScript similar to:
// Transpiled JavaScript
(_a = window.open(externalUrl, '_blank')) === null || _a === void 0 ? void 0 : _a.focus();
This approach stores the result of window.open()
in a variable, akin to what we did with
w</code earlier, ensuring that <code>focus()
is only invoked if the result is neither null nor undefined. Either method should suit your needs adequately.
I hope this explanation proves helpful; best of luck!
Link to Code Playground