Generics
What
Generics allow you to create reusable logic—such as functions, classes, and interfaces—that can work with many different types while still maintaining full type safety. Instead of hard-coding a specific type, you use a “type parameter” as a placeholder.
How
You define a generic using angle brackets with a type variable (conventionally T):
function getFirst<T>(arr: T[]): T | undefined {
return arr.length > 0 ? arr[0] : undefined;
}
const num = getFirst([1, 2, 3]); // num is typed as number
const str = getFirst(["a", "b"]); // str is typed as string
Why
Generics prevent you from having to rewrite the same logic for every possible data type. Without generics, you would either have to duplicate your code or resort to using any, which loses all the benefits of TypeScript. Generics provide the best of both worlds: extreme flexibility and perfect type information.
Summary
Generics are a way to share behavior across types without losing specific type information.