본문 바로가기
개발 공부 일지/TypeScript

타입스크립트 - Union, Intersection

by yelimu 2024. 9. 11.

타입스크립트의 타입은 Structural Subtyping 이라는 규칙을 따른다

:상속 관계가 명시되어 있지 않더라도 객체의 프로퍼티를 기반으로 사용처에서 사용함에 문제가 없다면 타입 호환을 허용하는 방식

interface A {
  a: string;
}

interface B {
  b: number;
}

function printA(arg: A) {
  console.log(arg.a);
}

const x = { a: 'codeit' };
const y = { b: 42 };
const z = { a: 'codeit', b: 42 };
const w = { a: 'codeit', b: 42, c: true };

printA(x);
printA(y); // 잘못된 타입
printA(z);
printA(w);

함수 printA 는 A 타입의 인자를 받아 a 프로퍼티 값을 출력한다. 

이때 {a }가 포함되어있는 x, z, w 를 타입 A 라고 판단하기때문에 오류가 나지않는다.


Union

A|B|C|D|...

function printAUnionB(arg: A | B) {
  // 여기서는 타입 A | B

    if ('a' in arg) {
    // 여기 안에서는 타입 A
    console.log(arg.a);
  }

    if ('b' in arg) {
    // 여기 안에서는 타입 B
    console.log(arg.b); // VS Code에서 arg에 마우스를 호버해 보세요.
  }
}

if in 구문을 사용해서, 해당 프로퍼티가 존재할때 조건문 실행 : Type Narrowing 이라고 한다. 

 

Intersection

A&B&C&D&...

interface A {
  a: string;
}

interface B {
  b: number;
}

function printAIntersectionB(arg: A & B) {
  console.log(arg.a);
  console.log(arg.b);
}

const x = { a: 'codeit' };
const y = { b: 42 };
const z = { a: 'codeit', b: 42 };
const w = { a: 'codeit', b: 42, c: true };

printAIntersectionB(x); // 타입 오류
printAIntersectionB(y); // 타입 오류
printAIntersectionB(z);
printAIntersectionB(w);

A&B 타입은 {a, b} 두 프로퍼티를 모두 가지고있는 타입

 

https://toss.tech/article/typescript-type-compatibility