Typescript 9. 합집합 타입

하비·2024년 3월 27일
0

typescript

목록 보기
9/14

Union Type

유니언 타입은 서로 다른 두 대 이상의 타입들을 사용하여 만듬.
유니언 타입의 값은 타입 조합에 사용된 타입 중 무엇이든 하나를 타입으로 가질 수 있다.
조합에 사용된 타입을 유니언 타입의 멤버라고 함

function printId(id: number | string) {
  console.log("Your ID is: " + id);
}
printId(101); // OK
printId("202"); // OK
printId({ myID: 22342 });  // Error !

Typescript에서 유니언을 다룰 때는 해당 유니언 타입의 모든 멤버에 대하여 유효한 작업일 때에만 허용됨. 예를 들어 string|number라는 유니언 타입의 경우, string 타입만 유효한 메서드는 사용 불가.

function printId(id: number | string) {
  console.log(id.toUpperCase());  // Error !
}

여기서 저 toUpperCase 메서드를 사용하고 싶다면 union type 의 범위를 좁혀주면 된다.

function printId(id: number | string) {
  if (typeof id === "string") {
    // 이 분기에서 id는 'string' 타입을 가집니다
    console.log(id.toUpperCase());
  } else {
    // 여기에서 id는 'number' 타입을 가집니다
    console.log(id);
  }
}

또는 isArray, isString 같은 함수를 사용

function welcomePeople(x: string[] | string) {
  if (Array.isArray(x)) {
    // 여기에서 'x'는 'string[]' 타입입니다
    console.log("Hello, " + x.join(" and "));
  } else {
    // 여기에서 'x'는 'string' 타입입니다
    console.log("Welcome lone traveler " + x);
  }
}

유니언의 모든 멤버가 공통적으로 갖고 있는 메서드의 경우 좁히기를 하지 않아도 사용 가능함.

// 반환 타입은 'number[] | string'으로 추론됩니다
function getFirstThree(x: number[] | string) {
  return x.slice(0, 3);
}//number[],string 둘 다 slice 메서드를 사용할 수 있음

타입별칭
똑같은 타입을 한 번 이상 재사용하거나, 또 다른 이름으로 부르고 싶을 때 사용함.

type Point = {
  x: number;
  y: number;
};
function printCoord(pt: Point) { //Point type을 pt로 별칭을 정함
  console.log("The coordinate's x value is " + pt.x);
  console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 100, y: 100 });

타입별칭 사용 시 객체 타입 뿐 아니라 모든 타입에 대해 새로운 이름을 부여할 수 있음.

type ID = number | string

타입 별칭은 단지 별칭에 지나지 않음. 동일 타입에 대한 여러 버전이 아닌, 그 타입을 지칭하는 여러 이름을 만드는 것이라 생각하면 됨

type UserInputSanitizedString = string;
function sanitizeInput(str: string): UserInputSanitizedString {
  return sanitize(str);
}
let userInput = sanitizeInput(getInput());
userInput = "new input";

union type 사용시 주의할 점

interface User {
  id: string;
  age: number;
}
interface Author{
  id: string;
  level:number;
}
function userPage(someone: User | Author){
  someone.id //정상 동작
  someone.age // error!
  someone.level // error!
}

타입 스크립트 관점에서는 둘 중 어떤 타입이 들어올 지 알 수 없기 떄문에 어떤 타입이 들어오든 간에 오류가 나지 않는 방향으로 타입을 추론한다.
때문에 공통 속성인 id만 접근할 수 있게됨

profile
개발자를 꿈꾸는 하비입니다

0개의 댓글