Generic Types
Functions and interfaces that work with any type
#generics #types #reusability
Generic Types
Generics allow you to write reusable code that works with multiple types.
Generic Function
function identity<T>(arg: T): T {
return arg;
}
const num = identity<number>(42);
const str = identity<string>("hello");
const auto = identity(true); // Type inferred
Generic Interface
interface Box<T> {
value: T;
}
const numberBox: Box<number> = { value: 123 };
const stringBox: Box<string> = { value: "hello" };
Generic Constraints
interface HasLength {
length: number;
}
function logLength<T extends HasLength>(arg: T): void {
console.log(arg.length);
}
logLength("hello"); // OK
logLength([1, 2, 3]); // OK
// logLength(123); // Error: number has no length
Multiple Type Parameters
function pair<T, U>(first: T, second: U): [T, U] {
return [first, second];
}
const result = pair<string, number>("age", 30);
Discover another handy tool from EditPDF.pro