01
Overview
Generics are type variables: function id<T>(x:T):T. Constraints with extends. Default type params. Multiple type params. Generic classes and interfaces. Infer in conditional types.
bash
function id<T>(x:T):T{return x;}
function get<T,O extends Record<string,T>>(o:O,k:keyof O):T{return o[k];}
// Generic class
class Box<T>{constructor(public v:T){}}
const b=new Box(42); // Box<number>
// Constraints
function len<T extends {length:number}>(x:T):number{return x.length;}02
Best Practices
Use generics for reusable data structures. Constrain with extends. Use keyof for property access. Use typeof for type from value. Avoid over-genericizing (simple is better). Use infer in conditional types. Document complex generics.)
Ready to try Generics?
Visit the official site for the latest version and full documentation.
Visit Generics