Advertisement
Advanced TypeScript, Index Signatures & Record Types

How do you use Record<K, V> in combination with Partial<> to type a lookup object where not every key is guaranteed to be populated yet?

Short answer

Wrap the Record type in Partial<> to make every key optional, which is the correct way to model an incrementally-built lookup object (like a cache or accumulator) that doesn't necessarily have every possible key populated from the start.

Save TypeScript mock interview
Advertisement
AModel answer
Wrap the Record type in Partial<> to make every key optional, which is the correct way to model an incrementally-built lookup object (like a cache or accumulator) that doesn't necessarily have every possible key populated from the start.
type Theme = 'light' | 'dark' | 'system';
const cache: Partial<Record<Theme, string>> = {};
cache.light = 'Light Mode'; // OK
console.log(cache.dark); // typed as string | undefined, correctly reflecting it may not exist yet
Real-world example
Modeling an in-memory cache keyed by a known finite set of values that gets populated gradually over the program's lifetime.
Likely follow-ups
  • Why is `Partial<Record<K,V>>` generally more correct here than a plain `Record<K, V>` with all keys pre-populated as empty strings?
Related topics