Skip to content

FlashcardNot attempted

Why generics

Recall it before you reveal

Why use generics instead of any? Give a one-line example.

Space to reveal
Show answer & explanation

Generics keep the relationship between input and output types while staying reusable. any throws that information away.

function first<T>(arr: T[]): T: pass number[], get number back; pass string[], get string. With any[] → any, every caller loses autocomplete and type checking.

Add constraints (<T extends { id: string }>) when the function needs to use something about T.