타입스크립트 리터럴 타입 예제

-

타입스크립트에서 리터럴( Literal ) 타입은 `success`, 200, true 와 같은 값을 타입으로 사용하는 방식이다.
문자열, 숫자, 불리언 리터럴 타입을 통해 값의 범위를 구체적으로 지정하여 사용한다.
타입스크립트 리터럴 타입은 상태 코드를 사용하는 것과 같은 효과를 볼 수 있다.

-

let status: string;

status = "loading";
status = "success";
status = "anything";

-

let status: "loading";

status = "loading"; // 가능
status = "success"; // 오류

-

function showMessage(type: string) {
  console.log(type);
}

showMessage("success");
showMessage("sucess"); // 오타지만 string이므로 통과

-

type MessageType = "success" | "error" | "warning";

function showMessage(type: MessageType) {
  console.log(type);
}

showMessage("success"); // 가능
showMessage("sucess"); // 오류

-

type ButtonSize = "small" | "medium" | "large";

function createButton(size: ButtonSize) {
  return `버튼 크기: ${size}`;
}

createButton("small"); // 가능
createButton("large"); // 가능
createButton("xlarge"); // 오류

-

type DiceNumber = 1 | 2 | 3 | 4 | 5 | 6;

function rollDice(number: DiceNumber) {
  return `주사위 숫자: ${number}`;
}

rollDice(3); // 가능
rollDice(7); // 오류

-

type Rating = 1 | 2 | 3 | 4 | 5;

function review(score: Rating) {
  return `평점은 ${score}점입니다.`;
}

review(5); // 가능
review(10); // 오류

-

type IsAdmin = true;

const adminOnly: IsAdmin = true;

// const userOnly: IsAdmin = false; // 오류

-

type OrderStatus = "pending" | "paid" | "shipped" | "cancelled";

function updateOrderStatus(status: OrderStatus) {
  console.log(`주문 상태: ${status}`);
}

updateOrderStatus("paid"); // 가능
updateOrderStatus("refund"); // 오류

-

type Toast = {
  type: "success" | "error" | "info";
  message: string;
};

const toast: Toast = {
  type: "success",
  message: "저장되었습니다.",
};

-

const wrongToast: Toast = {
  type: "danger", // 오류
  message: "문제가 발생했습니다.",
};

-

type Theme = "light" | "dark";

function setTheme(theme: Theme) {
  document.body.dataset.theme = theme;
}

setTheme("light"); // 가능
setTheme("dark"); // 가능
setTheme("blue"); // 오류

-

type ApiResponse =
  | { status: "success"; data: string[] }
  | { status: "error"; message: string };

function handleResponse(response: ApiResponse) {
  if (response.status === "success") {
    console.log(response.data);
  } else {
    console.log(response.message);
  }
}

-

const direction = "up";

-

const config = {
  mode: "dark",
};

-

const config = {
  mode: "dark",
} as const;

-

type Color = "red" | "blue";
type Size = "small" | "large";

type ClassName = `${Color}-${Size}`;

const class1: ClassName = "red-small"; // 가능
const class2: ClassName = "blue-large"; // 가능
const class3: ClassName = "green-small"; // 오류

-

댓글

타입스크립트 기본 타입 종류 | 변수 함수 객체 등에 지정하는 자료형

이미지
타입스크립트( Typescript )의 특징은 변수, 함수, 객체 등에 데이터 타입을 지정하여 오류를 줄이는 역할을 한다. 관대한 자바스크립트( Javascript )의 변수 지정에 데이터 타입을 지정하는 것이 타입스크립트이다. 자바스크립트에서는 변수에 어떤 값이든 자유롭게 넣을 수 있지만, 타입스크립트는 변수, 함수, 객체에 들어갈 값의 종류를 미리 지정할 수 있다. 자바 또는 C# 과 같은 언어들에 데이터 타입을 지정하는 것과 같다고 볼 수 있다. 타입스크립트의 타입에는 여러 종류가 있다. 굳이 나열하면 string, number, boolean, array, object, null, undefined, any, unknown, union, void 가 있다. 타입스크립트 기본 타입 종류 | 변수 함수 객체 등에 지정하는 자료형 ⊙ 타입스크립트 기본 타입 종류 타입스크립트는 자바스크립트에 자료형을 지정한 것이라 볼 수 있으며, 이것을 타입( type )이라 칭한다. 자바스크립트가 자료형에 관대한 특징이 있기 때문에, 의도하지 않은 코드 동작의 오류가 발생할 수 있다. 예를 들어, 자바스크립트의 + 연산자가 대표적인데, + 연산자는 숫자간 덧셈 연산도 하지만, 문자열에 + 가 들어간 경우 문자열 연결 동작을 하기 때문이다. 이 외에도 여러가지 경우들이 있다. 구구절절 말은 많았지만, 자바 또는 C# 처럼 자료형( 데이터 타입, data-type )을 지정한다고 보면 이해가 쉽다. 타입스크립트의 타입 자료형에는 여러가지가 존재하는데 그 중 일부는 다음과 같다. string : 문자열 number : 숫자 boolean : 참/거짓 array : 배열 string[] : 문자열 배열 number[] : 숫자 배열 type : 타입 별칭 interface : 객체 구조 string | number : 문자열 또는 숫자 object : 객체 타입 null : 값이 비어 있음 undefined : 값이 할당되어 있지 않음 any : 아무 타입이나 가능 unknown ...

이 블로그의 인기 게시물

ChatGPT Codex GitHub 연결 해제 방법 (앱 삭제까지 정리)

C언어 return 종류와 차이 | return, return 0, return -1, return n

챗지피티 코덱스와 깃허브 연동 방법 | VSCode 사용하기