0

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!

1
  • @jcalz You are right! Thanks. Instead of a comment maybe you should make this an answer so I can mark it a accepted Commented Apr 5, 2019 at 15:00

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.