Dhananjay Patel Logo
  1. Home
  2. / Blog
  3. / Typescript Api
  4. / Lessons
  5. / 4

Record vs Map

  • Record is a TypeScript utility that defines a type with a fixed set of keys and their corresponding types.
  • Map is a built-in JavaScript object that stores key-value pairs and offers more flexibility, especially when keys are not known ahead of time.

Record Example

interface User {
id: string;
name: string;
}
type UsersRecord = Record<string, User>;
const users: UsersRecord = {
'abc123': { id: 'abc123', name: 'John Doe' },
'def456': { id: 'def456', name: 'Jane Doe' },
};

Map Example

interface User {
id: string;
name: string;
}
const usersMap = new Map<string, User>();
usersMap.set('abc123', { id: 'abc123', name: 'John Doe' });
usersMap.set('def456', { id: 'def456', name: 'Jane Doe' });
console.log(usersMap.get('abc123')); // Output: { id: 'abc123', name: 'John Doe' }

Key Points:

  • Record is simpler and better when keys are known at compile-time.
  • Map is more flexible and better for dynamic key-value pairs.