5 min read
•Question 11 of 48mediumWhat are Generics in TypeScript?
Creating reusable components with generics.
What You'll Learn
- What generics are
- Generic functions
- Generic interfaces
What are Generics?
Generics allow you to create reusable components that work with multiple types while maintaining type safety.
code.tsTypeScript
// Without generics
function identity(arg: any): any {
return arg;
}
// With generics
function identity<T>(arg: T): T {
return arg;
}
const num = identity<number>(42); // number
const str = identity<string>("hi"); // string
const inferred = identity(true); // boolean (inferred)Generic Functions
code.tsTypeScript
function firstElement<T>(arr: T[]): T | undefined {
return arr[0];
}
const n = firstElement([1, 2, 3]); // number
const s = firstElement(["a", "b"]); // stringGeneric Interfaces
code.tsTypeScript
interface Box<T> {
value: T;
}
const numberBox: Box<number> = { value: 42 };
const stringBox: Box<string> = { value: "hello" };Multiple Type Parameters
code.tsTypeScript
function pair<K, V>(key: K, value: V): [K, V] {
return [key, value];
}
const p = pair("age", 30); // [string, number]