Assuming you're using an IDE, there's probably a red squiggly line that shows which part of the expression is the problem:
window.open(externalUrl, '_blank').focus(); // error
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//Object is possibly 'null'
Here, it's saying that window.open(externalUrl, '_blank')
is possibly null
, not that window
itself might be. So you don't have to check window
to address this particular error (although depending on the runtime JS environment you're using there may or may not be a window
. I'll assume there is one).
Anyway, the error you're seeing comports with the MDN documentation for Window.open()
, which says that if the window can't be opened the return value will be null
. To address this, you need to look at the return value, and only call focus()
on it if it's not null. Note that you can't do it this way:
if (window.open(externalUrl, '_blank')) {
window.open(externalUrl, '_blank').focus(); // still error
}
That's because the compiler does not believe that one successful call to window.open()
implies that a second call will also be successful. As far as the compiler knows, it's possible that the first call returns a Window
and the second call returns null
. That seems unlikely to me if you're calling it with the same arguments, but I can't say for certain that it would work. And besides, you don't really want to open two windows, do you?
So, how should we do it? A way that works with most version of TypeScript is just to save the result in a variable and test it:
const w = window.open(externalUrl, '_blank');
if (w) {
w.focus(); // okay now
}
In TypeScript 3.7 and up, there's support for the optional chaining operator, ?.
. This lets you write the above more tersely as:
window.open(externalUrl, '_blank')?.focus(); // okay also
Eventually you can expect the optional chaining operator to be part of JavaScript itself; until then, the above code emits to JavaScript as something like:
// JavaScript emitted
(_a = window.open(externalUrl, '_blank')) === null || _a === void 0 ? void 0 : _a.focus();
which saves the result of window.open()
into a variable (like we did with w
above) and then only calls focus()
on it if it's not null
or undefined
. Anyway, either way should work for you.
Okay, hope that helps; good luck!
Playground link to code