typescript record vs map

Release Date: Update date: Total Words: 367 Reading time: 2m by IP: 上海 Share Copy Url

In TypeScript, Record and Map are two different data structures that serve similar purposes, but with distinct differences.

Record

Record is a utility type in TypeScript that represents an object type with a set of properties. It’s a way to create an object type with a specific shape, where each property has a specific type.

Example:

type PersonRecord = Record<string, string>;

const person: PersonRecord = {
  name: 'John',
  age: '30'
};

In this example, PersonRecord is a type that represents an object with string keys and string values. The Record type takes two type parameters: the first is the type of the key, and the second is the type of the value.

Map

Map is a built-in data structure in JavaScript (and TypeScript) that represents a collection of key-value pairs. It’s similar to an object, but with some key differences:

  • Maps can have any type of key, not just strings.
  • Maps preserve the order of insertion.
  • Maps have a size property that returns the number of key-value pairs.

Example:

const personMap = new Map<string, string>([
  ['name', 'John'],
  ['age', '30']
]);

In this example, personMap is a Map instance with string keys and string values.

Key differences

Here are the main differences between Record and Map:

  • Type: Record is a utility type, while Map is a built-in data structure.
  • Key type: Record requires string keys, while Map can have any type of key.
  • Order: Record does not preserve the order of properties, while Map preserves the order of insertion.
  • Size: Record does not have a size property, while Map does.

When to use each

Use Record when:

  • You need to create an object type with a specific shape.
  • You want to ensure that the object has a specific set of properties.
  • You don’t care about the order of properties.

Use Map when:

  • You need to store a collection of key-value pairs with arbitrary keys.
  • You need to preserve the order of insertion.
  • You need to access the size of the collection.

In summary, Record is a utility type for creating object types with specific shapes, while Map is a built-in data structure for storing collections of key-value pairs. Choose the one that best fits your use case! 😊

Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数