Generics
Generic
A technique for writing reusable code by parameterizing types. Supported in Java, TypeScript, Rust, and others.
Generic
A technique for writing reusable code by parameterizing types. Supported in Java, TypeScript, Rust, and others.
Generics (Generic) is a programming technique that parameterizes types to write reusable components. It allows functions or classes to be specified with a type at the point of use, without being tied to a specific type. This makes it possible to reduce code duplication while maintaining type safety.
The key benefit of generics is compile-time type safety. Java's List<String> can store only strings, and adding a wrong type is caught as a compile error. Using Object can cause a ClassCastException at runtime, but generics prevent this at compile time.
In TypeScript, generics apply to functions, classes, and interfaces. Many built-in types, such as Array<T>, Promise<T>, and Map<K, V>, are generic. Using constraints (extends), you can also restrict a type parameter to types that implement a specific interface.
In Rust, generics work without performance degradation. The compiler generates separate code for each type used through monomorphization. This provides the convenience of generics without runtime overhead. Type constraints are expressed with trait bounds.
// TypeScript 제네릭 예제
// 제네릭 함수
function identity<T>(arg: T): T {
return arg;
}
const str = identity<string>("hello"); // 타입 명시
const num = identity(42); // 타입 추론
// 제네릭 인터페이스
interface Result<T, E> {
success: boolean;
data?: T;
error?: E;
}
// 제네릭 클래스
class Container<T> {
private value: T;
constructor(value: T) {
this.value = value;
}
getValue(): T {
return this.value;
}
}
// 제약 조건 (extends)
interface HasLength {
length: number;
}
function logLength<T extends HasLength>(arg: T): number {
console.log(arg.length);
return arg.length;
}
logLength("hello"); // OK - string has length
logLength([1, 2, 3]); // OK - array has length
// logLength(123); // Error - number doesn't have length
// 여러 타입 파라미터
function swap<T, U>(tuple: [T, U]): [U, T] {
return [tuple[1], tuple[0]];
}
const swapped = swap([1, "hello"]); // [string, number]
Frontend developer: "Our API call functions are nearly identical for every endpoint, differing only in the response type. There's a lot of code duplication."
Tech lead: "You can abstract it with a generic function. Try making it in the form fetch<T>(url): Promise<T>."
Frontend developer: "So if I specify the type at call time, the return value will be inferred as that type too."
Tech lead: "Yes, the Axios instance is implemented that way too. If you also accept the error type as a generic, it's even more complete."
Interviewer: "Please explain why and how generics are used, and their advantages."
Candidate: "You can write reusable code while maintaining type safety. Using any disables type checking, but with generics the type is determined at the point of use, enabling IDE autocompletion and compile error detection."
Interviewer: "Are you familiar with covariance and contravariance?"
Candidate: "Covariance is the case where, if T is a subtype of U, Container<T> is also a subtype of Container<U>. Contravariance is the opposite, and occurs in function parameter positions. TypeScript checks this strictly."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Reviewer: "This utility function returns any, so there is no type safety."
Author: "It's used with several types, so I used any. Is there a better way?"
Reviewer: "Use generics. If you let the return type be inferred from the input type, you can keep flexibility without any."
Author: "Understood. I'll also add a T extends constraint to prevent wrong types from being passed."