Skip to the solution
MediumFrontend9 min read

How does the 'in' operator narrow types?

736 views

The problem

Question presented to candidate: "You have a Payment union where a card has cardNumber and a bank transfer has iban. How does if ('iban' in payment) narrow it, and what are the cases where the in operator surprises people?"

What a strong answer should cover:

  • "key" in obj keeps the union members that declare key (required or optional) in the true branch and the members that do not declare it, or declare it optional, in the false branch
  • An optional property keeps that member in both branches, so the property can still be undefined
  • Since 4.9, a key that no member declares is added to the type as Record<"key", unknown>, which makes in useful on unknown / object input
  • Run-time semantics: in walks the prototype chain ("toString" in {} is true) and throws on primitives; Object.hasOwn checks own properties only and does not narrow
  • When to prefer a discriminant property over in, and why in is the right tool for unions you do not control

Code / implementation expected: Yes β€” a function that narrows a union of object types with in, ideally including an optional-property case.

  • narrowing
  • in

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 Β· 9 sections

Run the code

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

TypeScriptNarrowing a union of object types with in
TypeScriptUnknown input, the prototype chain, hasOwn and primitives

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 36 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 are declaration files (.d.ts)?

Continue