Loading lessons...
Generic Functions & Interfaces
Generic Functions & Interfaces
Generics allow creating reusable components that work over a variety of types while retaining type safety.
Generic Functions
Instead of using any, use a type parameter like <T>:
function identity<T>(arg: T): T {
return arg;
}
let num = identity<number>(42); // Explicit type argument
let str = identity("Hello World"); // Type inferred as string!
Generic Interfaces
Interfaces can also accept type parameters:
interface ApiResponse<Data> {
status: number;
message: string;
data: Data;
}
type UserResponse = ApiResponse<{ id: string; name: string }>;
type ProductsResponse = ApiResponse<string[]>;
Multiple Type Parameters
function pairValues<K, V>(key: K, value: V): [K, V] {
return [key, value];
}
TL;DR
- Generics use angle brackets
<T>to parameterize types. - They preserve exact type relationships between inputs and outputs.
- TypeScript can infer generic types automatically from argument values.