TypeScript Master (50 Qs)•Part 1: Basic & Foundational TypeScript (Junior / Entry-Level)
What are Generics and why are they necessary?
junior LevelCode ExampleTypeScript
In Simple Words: Generics allow you to write reusable, type-safe functions, classes, and interfaces that work over a variety of types rather than a single fixed type, capturing the argument type dynamically:
typescript
// Without Generics: Loses type safety (returns 'any')
function getFirstAny(arr: any[]): any { return arr[0]; }
// With Generics: Preserves exact type
function getFirst<T>(arr: T[]): T {
return arr[0];
}
const num = getFirst([1, 2, 3]); // Type inferred as number
const str = getFirst(["a", "b"]); // Type inferred as string