How to Use TypeScript Generics with Examples: A Beginner's Guide
Learn how to use TypeScript generics with easy examples to write flexible, reusable code. This beginner-friendly tutorial explains generics, steps to implement them, common mistakes, and best practices.
If you’re just starting with TypeScript, one powerful feature you should learn is generics. Generics allow you to write reusable and flexible functions, classes, and interfaces that can work with any data type while keeping type safety. In this tutorial, we’ll break down what generics are, how they work, and show you clear step-by-step examples to help you understand how to use them effectively.
Generics are like placeholders for types. Instead of writing a function or a class that works with only one specific data type, you can create a generic version that works for any type you provide. This means you can write more abstract, reusable code without losing the benefits of TypeScript's strong typing system. Generics are commonly used with functions, interfaces, and classes, and they often come up when learning about type constraints and union types.
function identity<T>(arg: T): T {
return arg;
}
const numResult = identity<number>(42); // numResult is number
const strResult = identity<string>('hello'); // strResult is string
// You can also let TypeScript infer the type:
const inferredResult = identity(true); // inferredResult is booleanTo use generics properly, you should explicitly declare a generic type parameter using angle brackets <> after the function or class name. Inside the function, use this generic type like a variable representing a type. TypeScript will enforce that your function works consistently with that type. For more complex cases, you can add constraints to generics to restrict what types they accept, which ties nicely into the concepts of interfaces and type aliases.
A common mistake is to overuse generics when they aren’t necessary, making code harder to read. Another error beginners make is forgetting to specify a type or misuse the generic type parameters, leading to incorrect type inference or loss of type safety. For example, not returning the generic type or mixing it improperly with any types can defeat the purpose. Learning to combine generics with mapped types and conditional types can help avoid many pitfalls.
In summary, TypeScript generics empower you to write code that adapts to different types while preserving type safety. By understanding and practicing how to declare and use generics in functions and classes, you’ll write cleaner, more flexible code. Remember to explore related topics like type inference, interfaces, and type constraints to get the most out of generics and TypeScript’s type system.