never 타입과 느낌표(non-null assertion)

모두의희망·2022년 12월 13일
0

TypeScript

목록 보기
3/11
post-thumbnail

빈배열 never를 조심하자!

try {
  const array = [];  //여기에 손을 올리면 never[]가 표시된다. string은 never에 할당할수 없다는 에러가 표시됨
    const array: string[] = [];
   array.push('hello');
}catch(error) {
   error;
}

빈배열을 만들면 never라는 타입이 생긴다.array에서는 아무타입이 올 수 없다. 따라서 const array: string[] = []; 처럼 반드시 타입을 설정 해야 함.

느낌표(non-null assertion)

  • 느낌표 비추
타입스크립트에서 또는은 | 한번이다.
const head = document.querySelector('#head')!;  
console.log(head);   

뒤에 느낌표( ! )는 head태그가 null이나 undefine이 아니라는 것을 보증하는 방식 null이 사라짐 느낌표 비추

  • 이건 추천
const head = document.querySelector('#head');
if (head) {
  console.log(head);
}

누가 태그 이름을 바꿀수도 있기 때문에(만약 head를 header로바꾸면?) (can not read property 에러가 발생...)null이 생길 수 있다. 따라서 if를 사용 하는게 안전하다.

profile
개발을 진정성 있게 다가가겠습니다.

0개의 댓글