Skip to the solution
MediumFrontend10 min read

What are generics and why are they useful?

1.0k views

The problem

Question presented to candidate: "What are generics in TypeScript? Show me a function where a generic is better than any, and tell me where you see generics in everyday code."

What a strong answer should cover:

  • A generic is a type parameter (<T>): a placeholder filled in per call or per use, so one piece of code works for many types without losing type information
  • Why not any: any switches checking off for the result, while T links the input type to the output type (first<T>(items: T[]): T | undefined)
  • Type arguments are usually inferred from the call, and can be passed explicitly (first<string>([])); a const result keeps a literal type
  • Generics appear on functions, type aliases, interfaces and classes: Array<T>, Promise<T>, Map<K, V>, Result<T, E>, a Stack<T>
  • Generics are erased: they do not exist at run time, so you cannot new T() or check typeof T
  • Rule of thumb: a type parameter should appear at least twice (relate two things); otherwise a plain type is simpler

Code / implementation expected: Yes β€” a small generic function (identity, first, pair) and ideally a generic interface or class.

  • generics

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptany versus a generic: inference and explicit type arguments
TypeScriptGeneric type aliases, interfaces and classes

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 21 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

What is ReadonlyArray and readonly tuple?

Continue