Generics allow functions to work with any type while preserving type information.
function identity<T>(value: T): T {
return value;
}
console.log(identity<string>("hello")); // Output: hello
console.log(identity<number>(42)); // Output: 42
// Array of numbers
let nums: Array<number> = [1, 2, 3];
// A Promise that resolves to a string
let fetchData: Promise<string> = new Promise((resolve) => resolve("Hi"));
// A Map of user ages
let userAgeMap: Map<string, number> = new Map();
// A Set of unique numbers
let uniqueNumbers: Set<number> = new Set([1, 2, 3]);
// Readonly array
let readonlyNumbers: ReadonlyArray<number> = [1, 2, 3];
// Creating an object type using Record
type UserMap = Record<string, number>;
Partial<>
Define a generic interface to create flexible data structures.
interface Backpack<T> {
add: (item: T) => void;
get: () => T;
}
// Declare a backpack that only accepts strings
declare const backpack: Backpack<string>;
// Usage example:
const item = backpack.get(); // item is inferred as string
backpack.add("new item");
// backpack.add(123); // Error: number is not assignable to string