Skip to the solution
EasyFrontend9 min read

How does type inference work in TypeScript?

895 views

The problem

Question presented to candidate: "A lot of TypeScript code has hardly any type annotations, yet it is fully typed. How does type inference work, where does it come from, and when do you still need to write types yourself?"

What a strong answer should cover:

  • Inference from initializers, array elements (best common type as a union), object literals and return statements; the result is fixed, not dynamic
  • Contextual typing: callback parameters and functions assigned to a typed variable get their types from context
  • Literal widening: const keeps "dark", let and object properties widen to string; as const and annotations prevent it
  • Limits: parameters are not inferred from call sites (TS7006 under noImplicitAny), empty arrays evolve, mixed arrays do not get a supertype
  • Control flow analysis narrows a variable after assignments and checks, separate from its declared type
  • Where to annotate: parameters, public return types, empty collections, object literals that must match a shape

Code / implementation expected: Optional β€” a few declarations with the inferred type stated, ideally proven with a compile-time check.

  • inference
  • basics

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

9 min read Β· 10 sections

Run the code

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

TypeScriptWhere inference happens, proven by compile-time checks
TypeScriptWhere inference stops or surprises you

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 3 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 nextEasy

What is the difference between interface and type?

Continue