Welcome back! I am Mihir, and in this lesson we will learn generics in TypeScript.
Generics let you write reusable code while keeping the exact type information.
The Problem
function identity(value: any): any {
return value;
}This works, but any removes type safety.
const result = identity("Mihir");TypeScript does not strongly preserve that result is a string.
Basic Generic Function
function identity<T>(value: T): T {
return value;
}T is a type parameter.
It means: "Whatever type comes in, the same type comes out."
Using a Generic Function
const name = identity("Mihir");
const age = identity(28);
const isActive = identity(true);TypeScript understands:
name; // string
age; // number
isActive; // booleanExplicit Generic Type
Usually TypeScript can infer the type.
But you can also write it explicitly:
const username = identity<string>("Mihir");This tells TypeScript that T is string.
Generic Arrays
function getFirst<T>(items: T[]): T {
return items[0];
}
const firstNumber = getFirst([10, 20, 30]);
const firstName = getFirst(["Mihir", "Alex"]);firstNumber is a number.
firstName is a string.
Why Generics Are Useful
Generics are useful when:
- the function should work with many types
- you want to avoid
any - you want input and output types to stay connected
- you are building reusable helpers
- you are modeling collections and API responses
Generic Type Alias
type ApiResponse<T> = {
data: T;
success: boolean;
};
type UserResponse = ApiResponse<{ id: number; name: string }>;ApiResponse<T> can wrap any data type.
Quick Recap
- Generics let code work with multiple types safely.
- A type parameter like
Tacts like a type variable. - Generics preserve relationships between input and output types.
- They are better than
anyfor reusable code. - TypeScript often infers generic types automatically.
Next up, we will learn Generic Functions →.