Intersection Types

kukudas·2022년 2월 9일
0

TypeScript

목록 보기
26/39

Introduction to TypeScript intersection types

intersection 타입은 여러개의 타입을 조합해서 새로운 타입을 만들어냄. 이렇게 만들어맨 타입은 조합한 타입들의 기능을 전부 가지고 있음.

타입을 합치려면 &연산자를 아래와 같이 사용하면됨.

type typeAB = typeA & typeB;

typeABtypeAtypeB의 property를 가지게됨.
반면에 union type은 | 연산자를 사용해서 typeAtypeB 중에 하나의 값을 가질 수 있게 하는거임.

let varName = typeA | typeB; // union type

다음은 3개의 인터페이스를 정의하고 2개의 intersection type을 선언했음.

interface BusinessPartner {
    name: string;
    credit: number;
}

interface Identity {
    id: number;
    name: string;
}

interface Contact {
    email: string;
    phone: string;
}

type Employee = Identity & Contact;
type Customer = BusinessPartner & Contact;

Employee 타입은 Identity타입과 Contact타입의 모든 property를 가지게 되고 Customer 타입은 BusinessPartner타입과 Contact타입을 가지게됨.

type Employee = Identity & Contact;

let e: Employee = {
    id: 100,
    name: 'John Doe',
    email: 'john.doe@example.com',
    phone: '(408)-897-5684'
};

let c: Customer = {
    name: 'ABC Inc.',
    credit: 1000000,
    email: 'sales@abcinc.com',
    phone: '(408)-897-5735'
};

추가로 아래처럼 2개보다 더 많은 타입을 합칠 수 있음.
아래에서 Identity타입과 BusinessPartnername이라는 property를 같은 타입을 가지고 있는데 이렇게 여러 타입을 합쳤을때 각각의 타입이 가지고있는 property의 이름이 동일할 경우 타입도 같아야함. 그렇지 않으면 에러발생함.

type Employee = Identity & BusinessPartner & Contact;

let e: Employee = {
    id: 100,
    name: 'John Doe',
    email: 'john.doe@example.com',
    phone: '(408)-897-5684',
    credit: 1000
};

type typeAB = typeA & typeB;

타입을 intersect 할때 타입의 순서는 아무 상관없음.
typeABtypeBA는 같음.

type typeAB = typeA & typeB;
type typeBA = typeB & typeA;
  • intersection type은 2개 이상의 타입을 조합하여 조합하는 타입들의 property들을 가진 새로운 타입을 생성함
  • 타입을 조합할때 타입의 순서는 아무 상관없음

출처

0개의 댓글

관련 채용 정보