유니온 타입

zimablue·2023년 8월 14일

typescript

목록 보기
7/18

유니온 타입은 | 을 사용하며, 특정 함수가 두 가지 타입을 모두 취하도록 선언할 수 있습니다.

let age: number | string = 21;
age = 23;
age = "24";

타입에도 사용할 수 있습니다.

type Point = {
  x: number;
  y: number;
};

type Location = {
  lat: number;
  long: number;
};

let coordinates: Point | Location = { x: 1, y: 34 };
coordinates = { lat: 321.213, long: 23.334 };





Type Narrowing

유니온 타입을 사용할 경우 매개변수의 타입에 따라 오류가 발생할 수 있습니다.
이때 타입을 확인하는 단계를 추가하여 오류를 해결할 수 있습니다.

// price가 string일 경우 에러가 발생합니다.
function calculateTax(price: number | string, tax: number) {
  // The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
  return price * tax;
}
function calculateTax(price: number | string, tax: number) {
  if (typeof price === "string") {
    price = parseFloat(price.replace("$", ""));
  }
  return price * tax;
}





배열 & 유니온

배열의 값의 타입이 통일되지 않았을 경우 any를 사용할 수 있습니다.
하지만 any는 범위가 넓기 때문에 type script를 사용하는 목적에 맞지 않습니다.

const stuff: any[] = [1, 2, 3, 4, true, 'asdas', {}];

유니온 타입을 활용하면 any를 사용할 때 보다 범위를 좁힐 수 있습니다.

 const stuff: (number | string)[] = [1, 2, 3, "das"];

이때 주의해야할게 있습니다.
아래와 같이 작성하게 된다면 '숫자 배열만을 갖거나 문자열 배열만을 갖는다'라는 의미인 것을 아셔야 합니다.

// Type '(string | number)[]' is not assignable to type 'number[] | string[]'.
const stuff: number[] | string[] = [1, 2, 3, "das"];

타입도 사용가능합니다.

type Point = {
  x: number;
  y: number;
};

type Loc = {
  lat: number;
  long: number;
};

const coords: (Point | Loc)[] = [];

coords.push({ lat: 321.213, long: 23.334 });
coords.push({ x: 1, y: 34 });





리터럴 타입 & 유니온

리터럴은 어떤 변수의 타입을 결정해 주는 값을 말합니다.
일반적으로 타입에 리터럴 값으로 특정 숫자나 문자를 작성하게 되면 작성값은 이외의 값으로 재할당할 수 없게 됩니다.

// 리터럴이 숫자 0인 값은 숫자 0 이외에는 다른 값을 가질 수 없음
let zero: 0 = 0;

//Type '1' is not assignable to type '0'
zero = 1

이렇게 사용하는 것은 일반적으로 의미가 없습니다.
하지만 리터럴 값을 유니온과 결합하여 사용하게 되면 다양한 옵션을 만들 수 있게 되면서 유용해집니다.

let answer: "yes" | "no" = "no";
answer = "yes";
type DayOfWeek =
  | "Monday"
  | "Tuesday"
  | "Wednesday"
  | "Thursday"
  | "Friday"
  | "Saturday"
  | "Sunday";

let today: DayOfWeek = "Friday"

0개의 댓글