TypeScript · Senior · Question 72 of 75

Why are explicit generic constraints better than casting inside a generic function?

function byId<T extends { id: string }>(items: T[], id: string): T | undefined {
  return items.find((i) => i.id === id);
}

Explanation

Casting ((i as any).id) hides mistakes; the constraint documents and checks the requirement.

Further reading

Problem with a question

TypeScript · Senior · question 72

Test yourself

Take the TypeScript · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz