Introduction to Generics

Duration: 15 min  •  Difficulty: Hard

Generics allow us to create components/functions that can work with various data types while maintaining type safety.

Box Analogy

Imagine a box (Box). It can contain anything (Books, Shoes, Toys), but once an item is put in, we want to ensure its content remains consistent.

main.ts
// T is a placeholder for any data type
function wrapInArray<T>(item: T): T[] {
return [item];
}
const stringArr = wrapInArray<string>("Tesla"); // Produces string[]
const numberArr = wrapInArray<number>(2024); // Produces number[]
console.log(stringArr);
console.log(numberArr);