Generics
- In Turkish
- jenerik türler
- Pronunciation
- juh-NAIR-iks
In short
Generics are a language feature that lets you write functions, classes, and types that work with many data types while still keeping full type safety.
What are generics?
Generics let you write code once and reuse it with different types without giving up type checking. Instead of writing one function for a list of numbers and another for a list of strings, you write a single function with a type parameter, usually named T, that stands in for whatever type the caller uses. TypeScript, Java, C#, Go, Rust, Swift, and Kotlin all support generics, and Python offers them through type hints.
When you call a generic function or create a generic class, the type parameter is filled in with a concrete type, either explicitly, as in Box<string>, or automatically through type inference. The compiler then checks that every use is consistent, so a Box<string> can't accidentally hold a number. You can also add constraints, such as T extends { id: number }, to require that the type has certain properties.
A good analogy is a storage box with a label holder: every box has the same design, but once you label one 'books', only books go inside. Generics appear everywhere in everyday code, from built-in collections like Array<T>, Map<K, V>, and Promise<T> to API clients and data repositories that return typed results.
Generics are often confused with any in TypeScript or Object in Java. Using any switches type checking off, while a generic keeps track of the exact type, so the value you get out has the same type as the value you put in. Languages also handle generics differently at runtime: Java and TypeScript erase the type information after compiling, while C# keeps it and Rust generates specialized code for each type used.
Key takeaways
- Generics let one function, class, or type work safely with many types.
- A type parameter such as
Tis a placeholder filled in by the caller or by type inference. - The compiler still checks types, unlike
any, which turns checking off. - Constraints limit which types are allowed, for example
T extends { id: number }. - Built-in types like
Array<T>,Map<K, V>, andPromise<T>are generic.
Example
// One function that works with arrays of any type
function first<T>(items: T[]): T | undefined {
return items[0];
}
const n = first([10, 20, 30]); // n: number | undefined
const s = first(["a", "b"]); // s: string | undefined
// A generic class with a constraint: T must have a numeric id
class Repository<T extends { id: number }> {
private items: T[] = [];
add(item: T): void { this.items.push(item); }
findById(id: number): T | undefined { return this.items.find((i) => i.id === id); }
}Readers ask
What does T mean in generics?
T is a conventional name for a type parameter, short for type. It is a placeholder that gets replaced with a real type, such as number or User, when the generic code is used; other common names are K and V for keys and values.
What is the difference between generics and any in TypeScript?
any turns off type checking, so TypeScript forgets what type a value has. A generic remembers the exact type, so if you pass in a string you get a string back, and mistakes are still caught at compile time.
Does JavaScript have generics?
No. JavaScript is dynamically typed, so every function already accepts values of any type, but without compile-time checks. Generics come from TypeScript and are removed when TypeScript is compiled to JavaScript.
See also
- Data TypeProgramming Fundamentals, p. 14A data type is a classification that tells a program what kind of value a piece of data holds, such as a number or text, and which operations work on it.
- Type InferenceProgramming Fundamentals, p. 55Type inference is a compiler feature that works out the type of a variable or expression automatically, so you don't have to write every type annotation.
- TypeScriptWeb Development, p. 50TypeScript is a programming language built on JavaScript that adds static types, catching many bugs before the code runs, and compiles to plain JavaScript.
- ClassProgramming Fundamentals, p. 9A class is a blueprint in object-oriented programming that defines the data and behavior shared by a group of objects, which are created from it as instances.
- FunctionProgramming Fundamentals, p. 21A function is a named, reusable block of code that performs a specific task, optionally taking inputs called parameters and returning a result.
- ArrayProgramming Fundamentals, p. 3An array is an ordered collection of values stored under one name, where each item is accessed by its numeric position, called an index, usually starting at 0.
- IteratorProgramming Fundamentals, p. 31An iterator is an object that lets code step through the items of a collection one at a time, remembering its position, without exposing how the data is stored.
Spotted a mistake or something missing on this page?Suggest an edit