[TypeScript] 타입 별칭 (Type Alias)

2024. 11. 10. 01:31·TypeScript
728x90
728x90

타입 별칭 (Type Alias)

  - 특정 타입/인터페이스 등을 참조할 수 있는 타입 변수
  - 재선언 불가능

type userName = string;
type userName = number; // 에러 발생

  - 활용
     · 해당 타입이 어떤 역할을 하는지 이름을 짓고 싶을 때
     · 여러 번 반복되는 타입을 변수화해서 쉽게 표기하고 싶을 때
 

# 선언하기

// 기본 타입 별칭
type UserName = string;

// 객체 타입 별칭
type User = {
    name: string;
    age: number;
}

// 유니언 타입 별칭
type Message = string | number;
type Status = "success" | "error" | "loading";

// 제네릭 활용
type ApiResponse<T> = {
    code: number;
    data: T;
}

# 사용하기

let myName: UserName = "yang";

function logMessage(message: Message) {
    console.log(message);
}

 


타입 별칭과 인터페이스 비교

# 기본 문법

// 타입 별칭
type UserType = {
  id: number;
  name: string;
};

// 인터페이스
interface UserInterface {
  id: number;
  name: string;
}

# 확장 가능성

인터페이스 타입 별칭
상속과 확장 가능 기존 타입에 속성을 추가할 수 없음
=> 확장하려면 인터섹션 연산자를 사용해야 함
동일한 이름으로 인터페이스를 여러 번 선언하면 합쳐짐
: 선언 병합 (Declaration Merging)
동일한 이름으로 선언할 수 없음 (에러 발생)
// 인터페이스
interface User {
  id: number;
  name: string;
}

// 기존 인터페이스에 속성을 추가함
interface User {
  email: string;  
}

const user: User = {
  id: 1,
  name: "Alice",
  email: "alice@example.com",
};

--------------------------------

// 타입 별칭
type Person = {
  id: number;
  name: string;
};

// 인터섹션으로만 확장 가능
type Employee = Person & { role: string };

# 유니언 타입

인터페이스 타입 별칭
유니언 타입을 정의할 수 없음 유니언 타입 등 복합 타입을 정의할 수 있음
type Status = "success" | "error" | "loading";

# 함수 및 배열 타입 표현

  - 타입 별칭을 사용하면 인터페이스보다 더 간결하게 사용할 수 있음

// 타입 별칭
type StringArray = string[];
type Callback = (text: string) => void;

// 인터페이스
interface CallbackInterface {
  (text: string): void;
}

# 클래스

인터페이스 타입 별칭
클래스 구현에 사용할 수 있음 클래스를 구현하는 데 사용되지 않음
interface Animal {
  name: string;
  makeSound(): void;
}

class Dog implements Animal {
  name = "Dog";
  makeSound() {
    console.log("Woof!");
  }
}
320x100
반응형

'TypeScript' 카테고리의 다른 글

[TypeScript] 타입 가드 (Type Guard)  (0) 2024.11.15
[TypeScript] 타입 추론 (Type Inference) & 타입 단언 (Type Assertion)  (0) 2024.11.12
[TypeScript] 유니언 타입 & 인터섹션 타입  (0) 2024.11.09
[TypeScript] 인터페이스 (Interface)  (0) 2024.11.08
[TypeScript] 기본 타입  (4) 2024.11.07
'TypeScript' 카테고리의 다른 글
  • [TypeScript] 타입 가드 (Type Guard)
  • [TypeScript] 타입 추론 (Type Inference) & 타입 단언 (Type Assertion)
  • [TypeScript] 유니언 타입 & 인터섹션 타입
  • [TypeScript] 인터페이스 (Interface)
스응
스응
    반응형
    250x250
  • 스응
    이서영의 개발 블로그
    스응
  • 전체
    오늘
    어제
  • 글쓰기 관리
    • 분류 전체보기 (385)
      • Java (134)
        • Base (54)
        • Spring Boot (37)
        • JSP (16)
        • Swing (GUI) (20)
        • Design Pattern (7)
      • C# (13)
      • PHP (18)
      • SQL (27)
      • Vue.js (9)
      • Tailwind CSS (4)
      • TypeScript (7)
      • HTML & CSS (27)
      • JavaScript (26)
      • jQuery (10)
      • Android (3)
      • - - - - - - - - - - - - - - (0)
      • Hotkeys (5)
      • CS (30)
      • IT Notes (13)
      • Error Notes (17)
      • Team Project (24)
        • Airlines Web Project (12)
        • University Web Project (6)
        • Strikers 1945 GUI Project (6)
      • My Project (18)
        • Library Web Project (8)
        • Pet Shopping Mall GUI Project (10)
      • etc. (0)
  • 블로그 메뉴

    • Home
    • Write
  • 링크

    • 깃허브
  • 공지사항

  • 인기 글

  • 태그

    js
    cs
    Android
    Hotkeys
    java
    Swing
    티스토리챌린지
    jsp
    SEO
    http
    개발일지
    오블완
    errorNote
    HTML
    SQL
    면접
    git
    CSS
    php
    zapier
    jQuery
    C#
    tailwindcss
    SWAGGER
    Codeigniter
    typeScript
    vuejs
    SpringBoot
    Wordpress
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.0
스응
[TypeScript] 타입 별칭 (Type Alias)
상단으로

티스토리툴바