← 가이드 목록으로 ← Back to guides

TypeScript 타입 시스템 완벽 가이드 Complete Guide to TypeScript Type System

TypeScript는 JavaScript에 정적 타입을 추가한 언어입니다. 컴파일 타임에 타입 에러를 잡아내어 런타임 버그를 크게 줄일 수 있습니다.

TypeScript adds static types to JavaScript. It catches type errors at compile time, significantly reducing runtime bugs.

기본 타입 Basic Types

// 기본 타입
let name: string = "TypeScript"
let age: number = 10
let isActive: boolean = true

// 배열
let numbers: number[] = [1, 2, 3]
let strings: Array<string> = ["a", "b"]

// 튜플
let tuple: [string, number] = ["hello", 42]
// Basic types
let name: string = "TypeScript"
let age: number = 10
let isActive: boolean = true

// Array
let numbers: number[] = [1, 2, 3]
let strings: Array<string> = ["a", "b"]

// 튜플
let tuple: [string, number] = ["hello", 42]

인터페이스와 타입 Interface and Type

// 인터페이스
interface User {
  id: number
  name: string
  email?: string // 선택적 속성
  readonly createdAt: Date
}

// 타입 별칭
type ID = string | number
type Status = 'active' | 'inactive' | 'pending'
// Interface
interface User {
  id: number
  name: string
  email?: string // 선택적 속성
  readonly createdAt: Date
}

// 타입 별칭
type ID = string | number
type Status = 'active' | 'inactive' | 'pending'

제네릭 Generics

제네릭은 타입을 매개변수화하여 재사용 가능한 컴포넌트를 만들 수 있게 합니다.

Generics allow creating reusable components by parameterizing types.

// 제네릭 함수
function identity<T>(arg: T): T {
  return arg
}

// 제네릭 인터페이스
interface ApiResponse<T> {
  data: T
  status: number
  message: string
}

const response: ApiResponse<User[]> = fetchUsers()
// Generic function
function identity<T>(arg: T): T {
  return arg
}

// Generic interface
interface ApiResponse<T> {
  data: T
  status: number
  message: string
}

const response: ApiResponse<User[]> = fetchUsers()

유틸리티 타입 Utility Types

// Partial: 모든 속성을 선택적으로
type PartialUser = Partial<User>

// Pick: 특정 속성만 선택
type UserBasic = Pick<User, 'id' | 'name'>

// Omit: 특정 속성 제외
type UserWithoutId = Omit<User, 'id'>

// Record: 키-값 쌍 타입
type UserMap = Record<string, User>
// Partial: 모든 속성을 선택적으로
type PartialUser = Partial<User>

// Pick: 특정 속성만 선택
type UserBasic = Pick<User, 'id' | 'name'>

// Omit: 특정 속성 제외
type UserWithoutId = Omit<User, 'id'>

// Record: 키-값 쌍 타입
type UserMap = Record<string, User>

💡 TypeScript 타자 연습 팁 💡 TypeScript Typing Practice Tips

타입 선언과 제네릭 문법을 반복 연습하면 TypeScript 코드 작성 속도가 크게 향상됩니다. 특히 <>, :, | 같은 특수 문자에 익숙해지세요.

Practicing type declarations and generic syntax repeatedly improves TypeScript coding speed. Get familiar with special characters like <>, :, and |.