TS) 리터럴 타입 활용 방법

rO_Or·2024년 1월 22일

간단한 공부

목록 보기
3/12

리터럴: 값 자체를 타입으로 사용을 한다.

type ImgType = "png"

const imgType: ImgType = "png"

type Direction = "left" | "right" | "up" | "down";

const nav = (dir: Direction) => {
  console.log(dir);
}

type btnType = "btn-default" | "btn-error" | "btn-success"
type btnSize = "sm"  | "md" | "lg"
type btnColor = "red" | "blue" | "color"

type buttonStyle = `${btnType}-${btnSize}-${btnColor}`

const addStyle = (el: HTMLElement, style: buttonStyle) => {
  el?.classList.add(style)
};

const languageCode = {
  en: "English",
  es: "Spanish",
  fr: "French",
  kr: "Korean"
}

languageCode.en = 'abc'; // 가능

const languageCode2 = {
  en: "English",
  es: "Spanish",
  fr: "French",
  kr: "Korean"
} as const

languageCode2.en = 'abc'; // error

// as const로 지정해주면 리터럴 타입이 되며, readonly 속성이 추가된다.
profile
즐거워지고 싶다.

0개의 댓글