728x90
// tsconfig.json
// + 추가
"strickNullCheck" : true // null type 엄격히 체크
<h4 id='title'> 안녕 </h4>
let 제목 = document.querySelector('#title')
제목.innerHTML('반가워요') // 에러 ) type이 element | null
/*
만약 let 제목 = document.querySelector('오타')
제목 === null
Selector로 찾은 요소는 ( element | null ) 이기 때문에,
narrowing을 해야함.
*/
narrowing 하는 방법
// 1
if(제목 != null){
제목.innerHTML='반가워요'
}
// 2. instanceof
if(제목 instanceof Element){
제목.innerHTML='반가워요'
}
// 3. ?. ) 옵셔널 체이닝
if(제목?.innerHTML){
제목.innerHTML='반가워요'
}
// 제목에 innerHTML이 있으면 출력, 없으면 undefined
// 2. as
let 제목 = document.querySelector('#title') as Element;
// -> 아이디 값이 오류여도, null이 아닌, Element(o)-> 지양...
링크 찾기
<a href="naver.com" class="link"> 링크 </a>
let 링크 = document.querySelector('.link')
if(링크 instanceof HTMLAnchorElement){ // 링크변경시, 정확한 type narrowing을 해야함.
링크.href='https: // ~'
}
이벤트 리스너
<button id="button"> 버튼 </button>
let 버튼 = document.querySelector('#button');
버튼?.addEventListener('click', function(){ // '버튼'에 addEventListener이 가능하면 하고, 아니면 undefined
event
})
728x90
'javascript' 카테고리의 다른 글
React typescript (0) | 2023.09.26 |
---|---|
타입스크립트 입문, 기본 문법 (0) | 2023.09.22 |
Array의 헷갈리는 메소드 정리(Array.from, arr.sort, arr.shift, arr.unshift) (0) | 2023.09.04 |
react-query 개념, 기본 문법 (0) | 2023.06.01 |
TypeScript 개념 (0) | 2023.03.27 |