핵심 답변
📌 제네릭(Generic)은 타입을 변수처럼 다루는 기능입니다. 하나의 함수나 인터페이스로 다양한 타입을 타입 안전하게 처리할 수 있습니다.
예시 코드
typescript
// 제네릭 없이: any를 사용하면 타입 안전성 쟁혼
function identity(arg: any): any { return arg; }
// 제네릭 사용: 타입 유지
function identity<T>(arg: T): T { return arg; }
const str = identity('hello'); // string 타입 유지
const num = identity(42); // number 타입 유지
// 실용적인 예: API 응답 타입
interface ApiResponse<T> {
data: T;
status: number;
message: string;
}
type UserResponse = ApiResponse<User>;
// 결과: { data: User; status: number; message: string; }핵심 용어
📌 타입 매개변수(Type Parameter)
<T>, <K, V> 같은 제네릭 타입 변수입니다. T(Type), K(Key), V(Value), E(Element) 등을 관례적으로 사용합니다.📌 타입 제약(Type Constraint)
<T extends string>처럼 제네릭 타입에 조건을 추가해 특정 타입만 허용하는 기능입니다.