모든 JavaScript 개발자가 길러야 할 10가지 TypeScript 습관 🚀
Source: Dev.to
TypeScript는 단순한 도구가 아니라 디버깅 도우미, 문서 시스템, 그리고 코드 안전망을 하나로 합친 것입니다. 이 10가지 습관을 통해 코딩 방식이 영원히 바뀔 것입니다.
1. Strict Mode 활성화
tsconfig.json에서 strict 모드를 항상 켜서 가장 포괄적인 타입 검사를 받으세요.
{
"compilerOptions": {
"strict": true
// …other options
}
}
2. 타입이 아닌 인터페이스 정의
type 별칭과 interface 선언 모두 객체 형태를 설명할 수 있지만, 인터페이스는 확장이 가능하고 계약을 정의하기에 이상적입니다.
interface User {
id: number;
name: string;
email: string;
}
3. any는 절대 사용하지 않기
any를 사용하면 TypeScript의 의미가 사라집니다. 대신 unknown, never 혹은 적절한 유니온 타입을 사용하세요.
function process(value: unknown) {
// narrow the type before using it
}
4. 유틸리티 타입 활용 (Pick, Omit, Partial)
TypeScript에 내장된 유틸리티 타입을 이용하면 기존 타입을 효율적으로 변형할 수 있습니다.
type User = { id: number; name: string; email: string };
type PartialUser = Partial; // all fields optional
type UserName = Pick; // only the name field
type UserWithoutEmail = Omit; // all except email
5. 타입 가드 사용
typeof, instanceof, 그리고 사용자 정의 체크를 통해 유니온 타입을 안전하게 좁힐 수 있습니다.
function isString(value: unknown): value is string {
return typeof value === "string";
}
// Usage
if (isString(someValue)) {
// `someValue` is now typed as `string`
}
6. 함수 반환 타입 명시
함수가 무엇을 반환하는지 항상 명시하여 의도치 않은 any 추론을 방지하세요.
function getUser(): User {
// implementation…
return { id: 1, name: "Alice", email: "alice@example.com" };
}
7. 고정된 값 집합에는 Enum 사용
Enum은 매직 문자열이나 숫자에 비해 가독성을 높이고 오타 위험을 줄여줍니다.
enum Role {
Admin = "ADMIN",
User = "USER",
}
8. 제네릭으로 재사용 가능한 코드 작성
제네릭을 사용하면 유연하고 타입 안전한 추상화를 만들 수 있습니다.
function identity(value: T): T {
return value;
}
// Example
const num = identity(42);
const str = identity("hello");
9. 외부 데이터 검증
외부 데이터를 무조건 신뢰하지 말고 API 응답에 대한 명시적인 형태를 정의하세요.
interface ApiResponse {
success: boolean;
data: User[];
}
10. TypeScript 추론 엔진 신뢰하기
TypeScript는 종종 타입을 올바르게 추론하므로, 보일러플레이트를 줄이면서도 안전성을 유지할 수 있습니다.
const users = [] as User[]; // inferred as User[]
Final Thought
TypeScript는 더 많은 코드를 쓰기 위한 것이 아니라, 더 안전하고 똑똑하며 예측 가능한 코드를 작성하기 위한 도구입니다. 디버깅에 소요되는 시간을 크게 줄이고 코드베이스를 깨끗하고 유지보수하기 쉽게 만들어 줍니다.