Skip to the solution
MediumFrontend11 min read

What are union and intersection types?

1.1k views

The problem

Question presented to candidate: "Explain union and intersection types. When would you reach for A | B versus A & B, and what happens to the members you are allowed to use in each case?"

What a strong answer should cover:

  • A union A | B means the value is one of the types; only members common to every member are usable until you narrow (typeof, in, a tag check)
  • An intersection A & B means the value is all of the types at once; it has every property of each part, which is how you compose object types
  • The counter-intuitive set view: a union of object types allows more values but fewer usable properties; an intersection allows fewer values but more properties
  • Incompatible intersections collapse: string & number is never, and a clash on a property makes that property (or, for literal tags, the whole object) never
  • Unions are not exclusive ({ x } | { y } accepts an object with both) and & silently produces never where interface extends reports a conflict
  • Practical uses: literal unions and discriminated unions for states, intersections for mixins, merge helpers and branded types

Code / implementation expected: Optional β€” narrow a string | number, and compose two object types with &.

  • union
  • narrowing

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.

TypeScriptUnions: shared members, narrowing and literal unions
TypeScriptIntersections: composing types, never and brands

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 19 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 do ReturnType and Parameters do?

Continue