Object Null in DOM Manipulation

Asked

Viewed 31 times

2

I’m new to Typescript and I have a problem that I’ve been trying to solve for a while.

I’m taking a random photo of an API and trying to insert it into an element div. However, I get the following compiler error:

(parameter) element: HTMLElement | null
Object is possibly 'null'. ts(2531)

One of the solutions was to disable the flag --strictNullChecks, but they say it’s not good practice.

Just follow my code:

const containerImg: 
HTMLElement | null = document.getElementById("container-img");

const handleWithImgFromApi: () => Promise<string> 
  = async() => {
      const url = "https://i.picsum.photos/id/338/200/300.jpg"
      const response = await fetch(url);
      return response.url;
};

const showImg: (element: HTMLElement | null) => void 
  = async(element: HTMLElement | null) => {
      const img: string = await handleWithImgFromApi();
      const template: string = `<img src=${img} />`

      element.innerHTML = template; //ERRO ACONTECE AQUI
}

showImg(containerImg);

1 answer

3


Any operation of query in the GIFT, such as querySelector may indeed return a Element or null, since there is no guarantee that the element will actually be on the page.

There is the option to disable the option --strictNullChecks, which, as you said yourself, is not good practice, as it may silence other possible mistakes.

Another way is to ensure, using a if, that the element will not be null:

const element = document.querySelector('.foo');

if (element) {
  // Element aqui será não nulo.
  console.log(element.textContent);
}

Link to the Typescript playground.

You can also ensure that the following code will not be executed if the type is null. This can be done, for example by using return within a function:

function getTextContent(selector: string) {
  const element = document.querySelector(selector);

  if (!element) {
    return null;
  }

  // Element aqui será não nulo.
  return element.textContent;
}

Link to the Typescript playground.

Typescript will infer the type based on the code. I consider this type of construction to be a type of type Guard.

Another option is to use non-zero assertion operator (!). Be careful not to confuse it with the logical operator NOT. Use only if you are sure that the element will not be null:

const element = document.querySelector('.foo');

element.textContent; // Object is possibly 'null'.

element!.textContent; // OK

Link to the Typescript playground.

Note that this operator, as well as disabling the flag --strictNullChecks, can silence any errors at compile time - so it is necessary to use it carefully and carefully. However, this operator has the advantage of not silencing errors in every application, only in a single location.

  • 1

    Thank you so much for your help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.