TypeScript 4.1 Template Literal Types 실무 적용기

문제 상황

사내 백오피스 프로젝트에서 API 경로를 문자열로 관리하다 보니 오타로 인한 404 에러가 종종 발생했다. 특히 동적 라우팅 파라미터가 포함된 경로에서 /users/:id 같은 패턴을 직접 문자열로 다루다 보면 실수가 잦았다.

// 기존 방식
const getUserPath = (id: string) => `/api/users/${id}`;
const path = getUserPath('123'); // 타입 체크 없음

Template Literal Types 적용

TypeScript 4.1에서 추가된 Template Literal Types를 활용해 경로 타입을 정의했다.

type APIVersion = 'v1' | 'v2';
type Resource = 'users' | 'posts' | 'comments';
type APIPath = `/api/${APIVersion}/${Resource}`;

// 동적 파라미터 포함
type UserPath = `/api/v1/users/${string}`;

const path: APIPath = '/api/v1/users'; // OK
const wrong: APIPath = '/api/v3/users'; // Error

라우터 헬퍼 함수 구현

실제 사용할 헬퍼 함수에 타입을 적용했다.

type IDParam = string | number;

function buildUserPath(id: IDParam): `/api/v1/users/${string}` {
  return `/api/v1/users/${id}`;
}

function buildPostPath(userId: IDParam, postId: IDParam) {
  return `/api/v1/users/${userId}/posts/${postId}` as const;
}

효과

타입 레벨에서 경로 형식을 강제하니 IDE에서 자동완성도 정확해지고, 잘못된 경로를 컴파일 단계에서 잡아낼 수 있었다. 아직 재귀적인 패턴이나 복잡한 경로 매칭은 한계가 있지만, 기본적인 API 경로 관리에는 충분히 유용했다.

다음에는 이를 확장해서 HTTP 메서드까지 타입으로 관리하는 방법을 시도해볼 예정이다.

TypeScript 4.1 Template Literal Types 실무 적용기