TypeScript: Generics
1. What are Generics?
Generics are used to create highly reusable components. They allow you to define functions or classes that can work with a variety of types rather than being restricted to a single one.
2. Generic Functions
A type parameter <T> is used to determine the type at the time of the function call.
function identity<T>(arg: T): T {
return arg;
}
let output1 = identity<string>("myString");
let output2 = identity<number>(100);
3. Generic Interfaces
Generics can also be applied to interfaces to make them more flexible.
interface Box<T> {
content: T;
}
const stringBox: Box<string> = { content: "Apple" };
const numberBox: Box<number> = { content: 123 };
4. Generic Constraints
Using the extends keyword, you can restrict the types that can be used with a generic to those that meet specific criteria.
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length); // Guaranteed to have a length property
return arg;
}
loggingIdentity({ length: 10, value: 3 });