How do you use a Record type with a union of string literals as keys to enforce that ALL cases are handled?
Short answer
Record requires an object literal assigned to it to include EVERY member of the union as a key — omitting one causes a compile error, making it a lightweight way to enforce exhaustive handling of a fixed set of cases in object form (as an alternative to a switch statement).
Advertisement
AModel answer
Record<UnionOfLiterals, ValueType> requires an object literal assigned to it to include EVERY member of the union as a key — omitting one causes a compile error, making it a lightweight way to enforce exhaustive handling of a fixed set of cases in object form (as an alternative to a switch statement).
type Theme = 'light' | 'dark' | 'system';
const themeLabels: Record<Theme, string> = {
light: 'Light Mode',
dark: 'Dark Mode',
system: 'Use System Setting'
// omitting any key here is a compile error
};Real-world example
Guaranteeing a lookup table of labels/icons/colors stays in sync with every possible value of a status or theme union.
Likely follow-ups
- What error message appears if you forget one of the required keys?
Related topics