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);
Thank you so much for your help!
– Thales Maia