TypeScript 실전 팁 모음

프로젝트에서 자주 쓰이는 TypeScript 패턴과 팁을 정리합니다.

🌱씨앗

TypeScript 실전 팁

TypeScript를 잘 활용하면 런타임 에러를 크게 줄일 수 있습니다. 이 글에서는 실전에서 자주 쓰이는 패턴을 모아봤습니다.

1. Discriminated Union

type Result<T> =
  | { success: true; data: T }
  | { success: false; error: string };
 
function handle(result: Result<string>) {
  if (result.success) {
    console.log(result.data); // 타입 자동 추론
  } else {
    console.error(result.error);
  }
}

2. satisfies 연산자

TypeScript 4.9에서 추가된 satisfies는 타입 검증과 추론을 동시에 할 수 있습니다.

const config = {
  port: 3000,
  host: "localhost",
} satisfies Record<string, string | number>;
// config.port는 number로 추론 (string | number가 아님)

3. 제네릭 활용

react-server-components에서 다루는 서버 컴포넌트에서도 제네릭은 유용합니다.

async function fetchData<T>(url: string): Promise<T> {
  const res = await fetch(url);
  return res.json() as T;
}

4. Branded Types

원시 타입에 의미를 부여하는 패턴입니다.

type UserId = string & { readonly __brand: "UserId" };
type PostId = string & { readonly __brand: "PostId" };
 
function getUser(id: UserId) { /* ... */ }

이 블로그를 만들 때도 TypeScript strict 모드를 사용했습니다. 첫 글에서 기술 스택을 확인할 수 있습니다.

이 글을 참조하는 글

관련 글

로컬 그래프