티스토리 뷰

TypeScript

[TypeScript] Type guards

Dongi 2022. 1. 21. 22:43

안녕하세요 동기 여러분! 오늘은 타입 좁히기의 첫 번째 시간 타입 가드에 대해 알아봅시다! 사실 이 내용은 여태껏 알아본 타입들의 맥락과 비슷하기 때문에 쉬울 것이라 예상합니다.

 

Type guards

타입스크립트가 타입을 좁히는 방법은 조건문을 사용하여 변수가 특정한 타입인지 아닌지를 확인하는 것입니다.

이것을 우리가 타입 가드(Type guard)라고 부릅니다!

 


 

간단한 생김새

function whatever(what: string | number) {
    if (typeof what ==='string'){
        // if문 내용
    }
}
  • 함수 whatever을 선언하는데 매개 변수로는 what을 사용하고 what의 타입은 유니온으로 string과 number입니다.
  • if문을 넣어서 what의 타입이 'string'일 경우 무언가 실행합니다.
  • 네~ if문이 들어간 저 부분이 조건문이고 typeof what === 'string'부분이 변수가 특정한 타입인지 아닌지를 확인하는 작업입니다. → 아~ 그래서 얘가 타입 가드구나!

 


간단한 예

function stringOrNumber(para: string | number) {
	if(typeof para === 'number') {
    	console.log('숫자가 감지되었습니다.');
    }
    
    if(typeof para === 'string') {
    	console.log('문자가 감지되었습니다.');
    }
}

console.log(stringOrNumber('아아 마시고 싶다!'));
console.log(stringOrNumber(41239870));

 

컴파일링

에러없이 넘어갑니다.

 

 

실행

출력도 잘 됩니다.

 


 

오늘의 느낌

어제 오늘 온타리오의 날씨가 예사롭지 않다 -20도까지 내려갔다... 

'TypeScript' 카테고리의 다른 글

[TypeScript] Narrowing with else  (0) 2022.01.22
[TypeScript] Using in with Type Guards  (0) 2022.01.21
[TypeScript] Unions with Literal Types  (0) 2022.01.21
[TypeScript] Common Key Value Pairs  (0) 2022.01.20
[TypeScript] Unions and Arrays  (0) 2022.01.20
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함