💻 Programming

Generic

Generics

A technique for parameterizing types. Improves code reusability and type safety.

📖 Detailed Explanation

A generic is a programming technique that receives a type like a parameter, allowing you to write code that works with a variety of types. Because the type is determined at compile time, it guarantees type safety without runtime errors while greatly reducing code duplication.

Before generics, handling every type meant using Object or any, or writing a separate function with identical logic for each type. With generics, a single function or class can safely handle any type, such as numbers, strings, or objects, which lets you follow the DRY (Don't Repeat Yourself) principle.

Generics are supported by most modern statically typed languages, including TypeScript, Java, C#, Go, and Rust. They are used as an essential feature in collections (arrays, lists, maps, etc.), API response handling, and utility functions in particular, and they play a key role when developing libraries or frameworks.

In practice, generics are used in many places, such as API response type definitions, store types in state management libraries, and Props types of React components. In TypeScript projects in particular, making good use of generics maximizes the IDE's autocompletion and type inference features, which can greatly increase development productivity.

💻 Code Example

// 1. 기본 제네릭 함수 - 타입을 매개변수로 받음
function identity<T>(value: T): T {
    return value;
}

// 사용 시 타입이 자동 추론됨
const num = identity(42);        // T = number
const str = identity("hello");   // T = string

// 2. 제네릭 인터페이스 - API 응답 타입 정의
interface ApiResponse<T> {
    data: T;
    status: number;
    message: string;
    timestamp: Date;
}

interface User {
    id: number;
    name: string;
    email: string;
}

// 사용자 API 응답
const userResponse: ApiResponse<User> = {
    data: { id: 1, name: "김철수", email: "kim@example.com" },
    status: 200,
    message: "성공",
    timestamp: new Date()
};

// 3. 제네릭 제약조건 (extends) - 특정 타입만 허용
interface HasLength {
    length: number;
}

function logLength<T extends HasLength>(item: T): void {
    console.log(`길이: ${item.length}`);
}

logLength("hello");        // 문자열은 length 있음 ✅
logLength([1, 2, 3]);      // 배열도 length 있음 ✅
// logLength(123);         // 숫자는 length 없음 ❌ 컴파일 에러

// 4. 제네릭 유틸리티 함수 - 배열에서 첫 번째 요소 추출
function first<T>(arr: T[]): T | undefined {
    return arr[0];
}

const firstNum = first([1, 2, 3]);     // number | undefined
const firstUser = first([userResponse.data]); // User | undefined

// 5. 제네릭 클래스 - 타입 안전한 스택 구현
class Stack<T> {
    private items: T[] = [];

    push(item: T): void {
        this.items.push(item);
    }

    pop(): T | undefined {
        return this.items.pop();
    }

    peek(): T | undefined {
        return this.items[this.items.length - 1];
    }

    isEmpty(): boolean {
        return this.items.length === 0;
    }
}

const numberStack = new Stack<number>();
numberStack.push(10);
numberStack.push(20);
console.log(numberStack.pop()); // 20 (number 타입)

🗣️ Say It Like This in Practice

💬 In a Meeting
"Instead of creating a new API response type every time, let's standardize it with an ApiResponse<T> generic. If only the data part takes a generic type, it can be reused across all endpoints."
💬 In an Interview
"Generics are a technique that guarantees type safety at compile time while increasing code reusability. Using any carries the risk of runtime errors, but generics support type inference and autocompletion, which also improves development productivity."
💬 In a code review
"This is receiving an Object here. How about changing it to a generic? If you enforce only the necessary properties with an extends constraint, you can use it safely without type casting."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Use generics instead of any

Using any means giving up type checking. If you think "let's just use any for now," it will come back later as a runtime error. If you don't know the type, use unknown or generics.

❌
Naming conventions for generic type parameters

Use meaningful names instead of single letters like T, U, and V. Giving them meaning with a T prefix, as in TData, TResponse, and TItem, improves code readability.

✅
Restrict the type range with constraints (extends)

A generic does not need to accept every type. Using extends to restrict it to types that have the required properties or methods lets you write safer code.

🔗 Related Terms

📚 Learn More