Skip to the solution
MediumFrontend8 min read

Can generics have default types?

308 views

The problem

Question presented to candidate: "Can a generic type parameter have a default? How does that interact with inference and with constraints, and where have you seen defaults used?"

What a strong answer should cover:

  • Yes: interface Box<T = string> β€” writing Box alone means Box<string>; defaults arrived in TypeScript 2.3
  • Rules: a parameter with a default is optional, required parameters cannot follow optional ones (TS2706), a default must satisfy its constraint (TS2344), and a default may refer to earlier parameters (<T, C = T[]>)
  • For function calls, inference wins: the default only applies when there is nothing to infer from (box() vs box(10)); with neither, T becomes unknown
  • No partial inference: pass one type argument explicitly and the rest come from their defaults, not from the arguments
  • Good defaults: unknown for parse/fetch helpers, a loose event map for an emitter, React typings such as useState<S = undefined>()

Code / implementation expected: Optional β€” a generic interface or function with a default, and one call where inference overrides it.

  • generic-defaults

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

8 min read Β· 10 sections

Run the code

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

TypeScriptDefault type parameters: syntax, rules and inference
TypeScriptDefaults in practice: unknown, no partial inference, emitters

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 54 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 structural typing?

Continue