Loading Depth Study
Preparing your workspace
Generics allow code to work with different types while preserving information about the actual type being used.
Without generics, developers may use any when they need reusable code, but that removes important type safety. Generics solve this by allowing a type to be supplied when the function or type is used. This makes utilities flexible while still preserving the relationship between inputs and outputs. Generics are common in reusable functions, collections, API response types, and React components.
A reusable API response type can work for users, courses, lessons, or any other data while keeping the actual result type known.
function getFirst<T>(items: T[]): T | undefined {
return items[0];
}
const firstCourse = getFirst<string>(["React", "Node.js"]);
const firstScore = getFirst<number>([80, 90, 95]);
console.log(firstCourse);
console.log(firstScore);The first example returns a string and the second returns a number while keeping both operations type-safe.