The Type Mapping, or Enum Mapping, pattern is a technique in TypeScript that uses the Record utility type to create objects with key-value pairs that are type-safe.
This pattern is often used to replace multiple conditional statements (if, switch) with a concise and type-safe mapping.
Consider a function like this:
type StatusTypeProps = 'A' | 'B' | 'C' | 'D' | 'E';
const getParsedStatusType = ({ statusType }: StatusTypeProps) => {
if (statusType === 'A') return 'Something';
if (statusType === 'B') return 'Something';
if (statusType === 'C') return 'Something';
if (statusType === 'D') return 'Something';
if (statusType === 'E') return 'Something';
return;
};
Functions like this tend to be long, repetitive, and hard to maintain, and type safety is not guaranteed.
RecordYou can solve this neatly using TypeScript’s Record utility type:
type StatusTypeProps = 'A' | 'B' | 'C' | 'D' | 'E';
const statusTypeMap: Record<StatusTypeProps, string> = {
A: 'Something',
B: 'Something',
C: 'Something',
D: 'Something',
E: 'Something',
};
// Usage
const getParsedStatusType = (statusType: StatusTypeProps) => statusTypeMap[statusType];
RecordRecord<Key, Value> offers several benefits:
In short, conditional statements enumerating all possible cases can be replaced with a type-safe mapping object.
RecordThe Record<K, T> type is defined as:
type Record<K extends keyof any, T> = { [P in K]: T; };
K (first generic): the key typeT (second generic): the value typeIn the example above, StatusTypeProps is the key type, and string is the value type.