logo
Search검색어를 포함하는 게시물들이 최신순으로 표시됩니다.
    Table of Contents
    [TS] 연산자를 이용한 타입 정의

    이미지 보기

    [TS] 연산자를 이용한 타입 정의

    • 22.06.14 작성

    • 읽는 데 4

    TOC

    Union Type(|)

    2개 이상의 type을 지정하고 싶은 경우

    function logMessage(value: string | number): void {
      console.log(value);
    }
    logMessage('hello');
    logMessage(100);
    

    |(pipe; or 표시) 사용


    Type Guard

    특정 타입으로 타입의 범위를 좁혀나가는(필터링 하는) 과정

    imageimage
    • if문을 사용하여 특정 type인 경우를 조건으로 한다면, if문 내부에서 해당 type의 메서드 사용 가능
    • Union Type의 장점

    cf) 임의로 오류 발생시키기

    function logMessage(value: string | number): string {
      if (typeof value === 'number') {
        return value.toLocaleString();
      }
      if (typeof value === 'string') {
        return value.toString();
      }
      throw new TypeError('value must be string or number')
    }
    
    • type guard를 통해서 여러 개의 type 내에 해당하지 않는 type인 경우
    • throw new TypeError(ErrMsg)를 통해 TypeError 발생

    Union Type의 특징

    여러 interface의 공통 속성에 대해서만 VS Code IntelliSense

    interface Developer {
      name: string;
      skill: string;
    }
    
    interface Person {
      name: string;
      age: number;
    }
    
    • 이러한 두 interface를 만들고, Union Type으로 인자를 받으면 아래와 같다.
    image

    만약 각각의 interface의 고유한 속성을 사용하고 싶다면?

    type guard를 이용해 type을 특정하여 if문 내부에서 사용


    InterSection Type(&)

    function askSomeone(someone: Developer & Person): void {
      ...
    }
    
    • Union Type과 비교되는 Intersection Type인 & 문자로 연결
    • someone에 점을 찍으면 아래와 같은 결과
    image
    • 두 interface의 속성을 모두 사용 가능
    • 의미상 someone 인자는 Developer와 Person interface가 가지는 모든 속성과 type을 포함하는 type

    Union Type과 Intersection Type의 차이

    Union Type

    함수에 전달하는 객체 인자의 세부 타입이 다른 경우에도 모두 수용

    interface Developer {
      name: string;
      skill: string;
    }
    
    interface Person {
      name: string;
      age: number;
    }
    
    function askSomeone(someone: Developer | Person): void {}
    askSomeone({ name: '디벨로퍼', skill: '웹 개발' })
    askSomeone({ name: 'hulk', age: 50})
    
    • 전달되는 객체 인자의 속성 type에 따라 interface를 다르게 인식하여 오류 발생 X

    Intersection Type

    지정된 interface의 모든 속성과 type을 함수에 전달하는 객체 인자가 가져야 함

    function askSomeone(someone: Developer & Person): void {}
    askSomeone({ name: '디벨로퍼', skill: '웹 개발', age: 25 })
    
    • 즉, intersection은 여러 interface(type)을 합친 새로운 하나의 interface(type) 역할
    profile

    FE Developer 박승훈

    노력하는 자는 즐기는 자를 이길 수 없다