Skip to the solution
HardFrontend11 min read

What does the infer keyword do?

382 views

The problem

Question presented to candidate: "What does the infer keyword do in TypeScript? Show me how you would use it to pull a type out of another type, like the return type of a function."

What a strong answer should cover:

  • infer X declares a new type variable inside the extends clause of a conditional type; TypeScript fills it in by matching the checked type against the pattern, and X is usable in the true branch
  • If the pattern does not match, the false branch is taken; infer is only legal in the extends clause (error TS1338 elsewhere)
  • It can sit in any position: return type, parameters, array element, tuple head or rest, a generic argument like Promise<infer V>, or a hole in a template literal type
  • Built-ins such as ReturnType, Parameters and InstanceType are written with it (added with conditional types in TypeScript 2.8)
  • Finer rules: one name in several covariant spots gives a union, in parameter spots an intersection; infer X extends C (TypeScript 4.7) constrains the match; overloaded functions infer from the last signature

Code / implementation expected: Yes β€” write a MyReturnType<F> or ElementOf<T> with infer, and explain the false branch.

  • infer

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

11 min read Β· 10 sections

Run the code

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

TypeScriptinfer in every position, the false branch and where infer is not allowed
TypeScriptCandidates, infer X extends C, overloads and generic functions

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 77 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 nextHard

What are covariance and contravariance?

Continue