← 목록으로 돌아가기

TypeScript 유용한 팁

2025-10-08

TypeScript 유용한 팁

TypeScript는 JavaScript에 타입 시스템을 추가한 언어입니다. 몇 가지 유용한 팁을 공유합니다.

1. 타입 추론 활용하기

TypeScript는 강력한 타입 추론 기능을 제공합니다:

// 타입을 명시하지 않아도 됩니다
const message = "Hello, World!"; // string으로 추론됨
const count = 42; // number로 추론됨
const isActive = true; // boolean으로 추론됨

2. Union 타입

여러 타입 중 하나를 허용할 수 있습니다:

type Status = "pending" | "success" | "error";

function handleStatus(status: Status) {
  // status는 세 가지 값 중 하나만 가능합니다
}

3. Utility 타입

TypeScript는 유용한 유틸리티 타입들을 제공합니다:

interface User {
  name: string;
  email: string;
  age: number;
}

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

// 일부 속성만 선택
type UserPreview = Pick<User, "name" | "email">;

// 일부 속성 제외
type UserWithoutAge = Omit<User, "age">;

4. Generic 사용하기

제네릭을 사용하면 재사용 가능한 컴포넌트를 만들 수 있습니다:

function identity<T>(arg: T): T {
  return arg;
}

const result1 = identity<string>("hello");
const result2 = identity<number>(42);

5. Type Guards

타입 가드를 사용하여 런타임에 타입을 좁힐 수 있습니다:

function isString(value: unknown): value is string {
  return typeof value === "string";
}

function processValue(value: string | number) {
  if (isString(value)) {
    // 여기서 value는 string입니다
    console.log(value.toUpperCase());
  } else {
    // 여기서 value는 number입니다
    console.log(value.toFixed(2));
  }
}

TypeScript를 사용하면 더 안전하고 유지보수하기 쉬운 코드를 작성할 수 있습니다! 💪