2.15 조건문과 비슷한 컨디셔널 타입이 있다

    타입스크립트에서는 조건에 따라 다른 타입이 되는 컨디셔널 타입(Conditional Type)이 있습니다.

    type A1 = string;
    type B1 = A1 extends string ? number : boolean;
    // type B1 = number
    
    type A2 = number;
    type B2 = A2 extends string ? number : boolean;
    // type B2 = boolean
    

    이번에도 extends 예약어가 사용되었습니다. 여기의 extends는 삼항연산자와 같이 사용됩니다.

    특정 타입 extends 다른 타입 ? 참일 때 타입 : 거짓일 때 타입

    특정 타입을 다른 타입에 대입할 수 있을 때 참이 됩니다. 다시 말해 특정 타입이 다른 타입의 부분집합일 때 참이 됩니다.

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.