티스토리 뷰

TypeScript

[TypeScript] Narrowing with else

Dongi 2022. 1. 22. 08:19

 

 

 

안녕하세요 동기 여러분! 헤헤 엠블럼을 하나 만들어 봤습니다ㅋㅋㅋ 오늘은 타입 좁히기의 세 번째 시간으로 if문에 else도 사용하여 타입을 좁혀 보도록 하겠습니다!!!

 

 

 

 

Narrowing with else

저번 시간에 이런 코드를 만들었었습니다.

type Bionic = {
    run: () => string;
}

type Mechanic = {
    drive: () => string;
}

const marine = { 
    run: () => '자! 가자, 가자!, 좋았어!, 한바탕 놀아볼까!'
}

const siegeTank = { 
    drive: () => '이동!, 전진 앞으로!, 기꺼이!'
}

function move(unit: Bionic | Mechanic) {
    if('run' in unit) {
    return unit.run();
    }

    if('drive' in unit) {
    return unit.drive();
    }
}

if문이 상당히 길어서 보기가 좀 그렇죠? else를 이용하여 바꾸어보겠습니다.

 

type Bionic = {
    run: () => string;
}

type Mechanic = {
    drive: () => string;
}

const marine = { 
    run: () => '자! 가자, 가자!, 좋았어!, 한바탕 놀아볼까!'
}

const siegeTank = { 
    drive: () => '이동!, 전진 앞으로!, 기꺼이!'
}

function move(unit: Bionic | Mechanic) {
    if('run' in unit) {
    	return unit.run();
    } else {
   	return unit.drive();
    }
}

네~ 우리가 알고 있는 그 if문의 else입니다. 

 

 

컴파일링 잘됨 - 확인

 

 

출력문 잘 나옴 - 확인

 

 

 

 


 

오늘의 느낌

오늘 저녁은 제육볶음을 먹을 건데 청경채도 볶아서 같이 먹어야겠당!!!

 

밈 출처 : http://www.quickmeme.com/p/3vwm3b/page/3
 

go home

go home - qm stories & news.

www.quickmeme.com

 

'TypeScript' 카테고리의 다른 글

[TypeScript] Interfaces and Types  (0) 2022.01.23
[TypeScript] Narrowing After a Type Guard  (0) 2022.01.23
[TypeScript] Using in with Type Guards  (0) 2022.01.21
[TypeScript] Type guards  (0) 2022.01.21
[TypeScript] Unions with Literal Types  (0) 2022.01.21
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/06   »
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
글 보관함