Web Development TypeScript Subjective
Oct 04, 2025

Explain generics in TypeScript with examples.

Detailed Explanation
Generics allow creating reusable components that work with multiple types while maintaining type safety. Basic Generic Function: function identity(arg: T): T { return arg; } let output = identity('Hello'); let numberOutput = identity(42); Generic Interface: interface GenericIdentityFn { (arg: T): T; } function identity(arg: T): T { return arg; } let myIdentity: GenericIdentityFn = identity; Generic Classes: class GenericNumber { zeroValue: T; add: (x: T, y: T) => T; } let myGenericNumber = new GenericNumber(); myGenericNumber.zeroValue = 0; myGenericNumber.add = function(x, y) { return x + y; }; Benefits: • Type safety without losing flexibility • Code reusability across different types • Better IntelliSense and error detection • Compile-time type checking.
Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback