Skip to the solution
MediumFrontend9 min read

How do you get a union of an object's values as a type?

207 views

The problem

Question presented to candidate: "You have a constant object mapping names to status strings. How do you get a type that is the union of its values, so a function only accepts those strings? Walk me through why each part is needed."

What a strong answer should cover:

  • The pattern (typeof Obj)[keyof typeof Obj]: typeof turns the value into a type, keyof gives its keys, and indexing with the whole key union gives the union of values
  • as const is required: without it the values widen to string and the "union" is just string
  • A reusable type ValueOf<T> = T[keyof T]; arrays use [number] instead ((typeof arr)[number])
  • The run-time side: the type is erased, so validating input needs Object.values(Obj) plus a type guard (and a widening cast for includes)
  • Pitfalls: ValueOf on an array or tuple also picks up length and method types; it is one level deep, so nested objects need a recursive helper
  • Trade-offs versus enum; as const satisfies Record<string, number> to check the shape while keeping literals

Code / implementation expected: Yes β€” derive the union from a constant object and use it as a parameter type.

  • enum
  • keyof

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.

TypeScriptThe recipe: as const, typeof, keyof and indexed access
TypeScriptRun-time validation, satisfies and the array and nesting traps

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 59 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 the Awaited utility type?

Continue