티스토리 뷰
TypeScript를 사용하면서 활용할 수 있는 팁들을 정리해보자!
유틸리티 타입으로 타입 재사용
- 이미 정의한 타입을 변형해서 사용 가능
interface User {
id: number;
name: string;
email: string;
password: string;
}
// 모든 속성을 선택적으로 — 수정 API에서 유용
type UpdateUser = Partial<User>;
// 일부 속성만 골라서 — 응답 데이터 타입으로 유용
type PublicUser = Pick<User, "id" | "name">;
// 일부 속성만 제외 — 민감한 정보 제거할 때
type SafeUser = Omit<User, "password">;
as const로 상수를 타입으로 활용
- 상수와 타입을 따로 관리하지 않아도 되니 편리
// status의 타입이 string으로 추론됨 — 너무 넓음
const STATUS = {
PENDING: "pending",
DONE: "done",
ERROR: "error",
};
// as const를 붙이면 리터럴 타입으로 좁혀짐
const STATUS = {
PENDING: "pending",
DONE: "done",
ERROR: "error",
} as const;
// 상수에서 타입을 뽑아쓸 수 있음
type Status = typeof STATUS[keyof typeof STATUS];
// "pending" | "done" | "error"
제네릭으로 재사용 가능
- API 호출 함수를 엔드포인트마다 생성하지 않고 제네릭으로 하나로 사용 가능
// 엔드포인트마다 따로 만드는 경우
async function getUser(): Promise<User> {
const res = await fetch("/api/user");
return res.json();
}
async function getPost(): Promise<Post> {
const res = await fetch("/api/post");
return res.json();
}
// 제네릭으로 하나로
async function fetchData<T>(url: string): Promise<T> {
const res = await fetch(url);
return res.json();
}
const user = await fetchData<User>("/api/user");
const post = await fetchData<Post>("/api/post");
타입 가드로 분기 처리
- as로 강제 캐스팅 시 런타임 에러로 이어질 수 있기 때문에 타입 가드로 분기하는 것이 좋음
interface AdminUser {
role: "admin";
accessLevel: number;
}
interface GuestUser {
role: "guest";
}
type UserType = AdminUser | GuestUser;
// 타입 가드 함수
function isAdmin(user: UserType): user is AdminUser {
return user.role === "admin";
}
function handleUser(user: UserType) {
if (isAdmin(user)) {
console.log(user.accessLevel); // AdminUser로 좁혀짐
} else {
console.log("guest입니다");
}
}
never로 분기 누락 방지
- 새로운 타입이 추가됐을 때 never를 활용하여 컴파일 단계에서 처리
type Shape = "circle" | "square" | "triangle";
function getArea(shape: Shape) {
switch (shape) {
case "circle": return "원 넓이 계산";
case "square": return "사각형 넓이 계산";
case "triangle": return "삼각형 넓이 계산";
default:
const _exhaustive: never = shape; // 모든 케이스가 처리됐는지 체크
throw new Error(`처리되지 않은 shape: ${shape}`);
}
}'JavaScript' 카테고리의 다른 글
| JavaScript 흔한 실수 모음 (0) | 2026.02.24 |
|---|---|
| Javascript - ECMAScript 버전 히스토리 (0) | 2026.02.05 |
| 메모리 누수 원인 (0) | 2026.02.03 |
| JavaScript - Canvas 차트 모바일 화질 저하 문제 (0) | 2024.04.26 |
| JavaScript - 전화번호에 하이픈 추가 (0) | 2024.03.28 |