어떤 유형의 값이 2가지가 들어 올 때, 그 중 1가지가 null인 즉, 데이터가 없는 케이스에서 무작정 데이터가 당연히 있다고 생각하고 속성을 접근했을 경우, 잊지 않고 null을 체크하라!
const container: HTMLElement | null = document.getElementById("root"); let template = ` <div class="bg-gray-600 min-h-screen"> <div class="p-4 text-2xl text-gray-700"> {{__news_feed__}} </div> </div> `;
변수 container의 반환값으로 "null"이 아닌 경우에만, "innerHTML"에 접근하라!
수도코드 : 만약, 변수 container의 값이 null 이 아닌 경우, innerHTML에 접근한다.
if(container != null) {
container.innerHTML = template;
} else {
console.error(
"최상위 컨테이너(root)가 없어 UI를 진행하지 못합니다.")
}
이때, 코드를 축약할 수 있다.
변수 container를 if문 안에 넣었을 때, if 문에서 null 자체를 참, 거짓을 판별하여, null이 있다면, 거짓으로 판정해준다.
이를 적용하여, 변수 container에 데이터가 들어있다면, 참으로 판정하게 된다.
if(container) {
container.innerHTML = template;
} else {
console.error(
"최상위 컨테이너(root)가 없어 UI를 진행하지 못합니다.")
}
만약, 위 코드가 중복된다면, 함수로 업데이트하여 사용하는 것이 좋다.
function updateView(html) {
if(container) {
container.innerHTML = html;
} else {
console.error(
"최상위 컨테이너(root)가 없어 UI를 진행하지 못합니다.")
}
}
updateView(template)