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]:typeofturns the value into a type,keyofgives its keys, and indexing with the whole key union gives the union of values as constis required: without it the values widen tostringand the "union" is juststring- 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 forincludes) - Pitfalls:
ValueOfon an array or tuple also picks uplengthand 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.