본문으로 건너뛰기

아이템22

타입 좁히기

  • 일반적로 조건문을 이용해 타입을 좁힌다.
null 체크
분기문에서 예외를 던지거나 반환
instanceof
속성 체크 ('a' in ab)
Array.isArray 같은 일부 내장 함수로도 가능

isArray 사용법

function contains(text: string, terms: string | string[]) {
const termList = Array.isArray(terms) ? terms : [terms];
termList; // 타입이 string[]
}

명시적 태그 붙이기

interface UploadEvent { type: 'upload' }
interface DownloadEvent { type: 'download' }
type AppEvent = UploadEvent | DownloadEvent;
function handleEvent(e: AppEvent) {
switch(e.type) {
case 'download':
e; // 타입이 DownloadEvent
break;
case 'upload'
e; // 타입이 UploadEvent
break;
}
}

사용자 정의 타입가드

function isInputElement(el: HTMLElement): el is HTMLInputElement {
return "value" in el;
}

function getElementContent(el: HTMLElement) {
if (isInputElement(el)) {
el; // 타입이 HTMLInputElement
return el.value;
}
A;
el; // 타입이 HTMLElement
return el.textContent;
}