Mastering TypeScript Generics for High-Performance Code Reuse
Learn how to use TypeScript generics to create reusable and type-safe code that boosts performance and maintainability in your projects.
TypeScript generics allow you to write flexible, reusable functions and components that work with a variety of data types without sacrificing type safety. This tutorial will guide you through the basics of generics and show you how to apply them effectively for high-performance code reuse.
Imagine you want a function to return the first element of an array. You might write it like this using any:
function getFirstElement(arr: any[]): any {
return arr[0];
}While this works, you lose type information. If you pass an array of strings, you don't get the benefit of TypeScript knowing the return type is a string. Instead, let's use generics to improve this:
function getFirstElement<T>(arr: T[]): T {
return arr[0];
}Here,
Generics also work well with interfaces. Suppose you have a function that returns an object with a value and a timestamp:
interface Timestamped<T> {
value: T;
timestamp: number;
}
function wrapInTimestamp<T>(value: T): Timestamped<T> {
return {
value,
timestamp: Date.now()
};
}This function takes any value and returns it wrapped with a timestamp. Using generics, you keep the original type information intact, improving both reusability and type safety.
Generics can also be constrained to certain types using the `extends` keyword. For example, if you only want to accept types that have a `length` property, you can do:
function logLength<T extends { length: number }>(item: T): T {
console.log(item.length);
return item;
}This ensures `item` must have a `length` property (like strings or arrays), preventing misuse with types that don't support length.
Finally, generics are widely used in TypeScript’s standard library and popular frameworks. Mastering them will help you write cleaner, more general, and performant code. Experiment by converting your current functions to generic versions and see how much more flexible your code becomes!