Generics make your code more flexible by allowing it to work with any type while preserving type safety. Think of them as "type variables" you can reuse in classes, functions, and interfaces.
<T>
to declare a generic type. It can be named anything — T
, U
, ItemType
, etc.
<T>
defines a type placeholderidentity<string>("text")
, or let TypeScript infer itclass Box{ value: T; constructor(value: T) { this.value = value; } getValue(): T { return this.value; } } const numberBox = new Box (123); console.log(numberBox.getValue());