Pedro Rodriguez
Pedro Rodriguez

Reputation: 69

How to make Typescript compiler know when a variable is not null?

I'm using typescrip 3.4 with React and I'm trying to load the Youtube Iframe API with this code

const tag = document.createElement("script");
tag.src = "www.youtube.com/player_api";
const firstScriptTag = document.querySelector("script");
if (firstScriptTag != null) {
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}

Even though I'm checking if the variable is null, React will refuse to compile since the TS compiler is throwing the Object is possibly 'null' error

I have also tried using the non-null assertion operator ("!") like this

firstScriptTag!.parentNode.insertBefore(tag, firstScriptTag);

And the problem persists.

I know I can get rid of it by setting strict=false in the tsconfig file but I want to force myself to write good quality code.

Thanks in advance!

Upvotes: 0

Views: 162

Answers (1)

jcalz
jcalz

Reputation: 330061

The warning is on firstScriptTag.parentNode. You have to check both firstScriptTag and firstScriptTag.parentNode before you can safely call a method on firstScriptTag.parentNode:

if (firstScriptTag && firstScriptTag.parentNode) {
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); // no error
}

Hope that helps. Good luck.

Upvotes: 1

Related Questions