ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [TypeScript] Any, Union, Type Aliases, Type Guard
    개발 여정/FrontEnd 2023. 3. 2. 16:01

     

     

    TypeScript.

      Any, Union, Type Aliases, Type Guard

     

    1. Any Type

    • Any 타입은 어떠한 타입이든 모두 할당받을 수 있는 타입을 말한다.

     

    예시

     

    let anyValue: any = 3; // 숫자 타입 할당
    anyValue = 'Hello World'; // 다시 String 할당
    anyValue = true; // 다시 boolean  할당

     

    하지만 Any 타입은 변수 타입을 명확히 알 수 없는 경우에만 제한적으로 쓰는 것이다 좋다. (e.g. 3rd party library에서 동적 콘텐츠를 가져와서 변수 타입을 알 수 없을 때)
    변수 타입을 명확히 하는 것이 더 깔끔한 코드이기 때문이다.

     

     

     

    2. Union Type

    • Union Type은 몇 가지의 제한된 타입들을 동시에 지정하고 싶을 때 사용하는 타입이다.

     

    예시

     

    let unionValue: string | number; // 문자열과 숫자로 Union Type 할당
    unionValue = 'This is String'; // 문자열 값 할당
    unionValue = 5; // 숫자값 할당 (문제없음)
    unionValue = true; // boolean값 할당 -> 에러 발생! 

     

     

     

    3. Type Aliases

    • type 기호를 사용해서 타입 할당
    • Union Type을 여러 번 할당해서 코드가 어지러울 경우, Type Aliases를 이용해서 깔끔하게 정리할 수 있다.

     

    Type Aliase로 정리 전: number | string 지정이 여러 번 할당되어 있어 코드가 지저분하다.

     

    type StrOrNum = number | string;
    let totalCost: number;
    let orderID: number | string;
    
    const calculateTotalCost = (price: number | string, qty: number)
    : void => {
    
    }
    
    cosnt findOrderID = (customer: { customerID: number | string, name: string }, productID: number | string): number | string => {
        return orderID;
    }

     

     

    Type Aliase로 정리 후: StrOrNum로 정리되어 깔끔하다.

     

    type StrOrNum = number | string;
    let totalCost: number;
    let orderID: StrOrNum;
    
    const calculateTotalCost = (price: StrOrNum, qty: number)
    : void => {
    
    }
    
    const findOrderID = (customer: { customerID: StrOrNum, name: string }, productID: StrOrNum): StrOrNum => {
        return orderID;
    }

     

     

    4. Type Guard

    • UnionType을 사용할 때 코드 검증을 수행하는 것

     

    예시


    다음과 같이 number 변수에 number | string 유니언 타입을 부여했을 때,

     

     

    다음과 같은 에러 메시지가 뜬다.

     

     

    해결책

    • typeof 연산자와 조건문을 사용한다.
      ※ typeof: 변수의 데이터 타입을 반환

     

     

    참조

    https://www.youtube.com/watch?v=SVtqhpboxGw&list=PLJf6aFJoJtbUXW6T4lPUk7C66yEneX7MN&index=8 

Designed by Tistory.