본문 바로가기
Frontend/TypeScript(완)

[TS] TS연습하기4

by VictorMeredith 2023. 4. 12.

TypeScript

//함수 type 저장해서 사용하는 법 (Type Alias)
type 함수타입 = (a:string) => number;
const 뻥션1:함수타입 = (a) => 3

//Object 자료
const obj1:{name:string, count:number, func:()=>void} = {
  name : 'kim',
  count: 1,
  func : ()=>{
    obj1.count++
  }
}

//TypeScript를 사용하면서 DOM조작할 때 주의할 점
const 제목 = document.querySelector('#title')
if(제목 instanceof Element){ //instanceof 를 이용한 narrowing을 해준다. (좋은방법)
  제목.innerHTML = 'ㅇㅇㅇㅇ'
}
if(제목?.innerHTML){ // innerHTML이 있으면 출력, 없으면 undefined를 남겨준다. (옵셔널 체이닝, 2020이후)
  제목.innerHTML = '우웅'
}

//링크일때 
const 링크 = document.querySelector('.link');
if(링크 instanceof HTMLAnchorElement){ //상세한 타입체크가 강제.
  링크.href = 'https://www.naver.com'
}

//버튼일때 이벤트리스너 부착할 때
const 버튼 = document.querySelector('#button')
버튼?.addEventListener('click', ()=>{}) //이 경우 옵셔널체이닝도 narrowing으로 인정해준다.

//여러개의 HTML 리스트 array에 담고 변경하기
const htmlArr:NodeListOf<Element> = document.querySelectorAll('.naver')
htmlArr.forEach(e =>{
  if(e instanceof HTMLAnchorElement){
    e.href = 'https://www.naver.com'
  }
})

'Frontend > TypeScript(완)' 카테고리의 다른 글

[TS] TS연습하기6  (0) 2023.04.12
[TS] TS연습하기5  (0) 2023.04.12
[TS] TS 연습하기3  (0) 2023.04.12
[TS] TS 연습하기2  (0) 2023.04.12
[TS] TS 연습하기1  (0) 2023.04.12

댓글