Home > Web Front-end > JS Tutorial > A Comprehensive Guide to Understanding TypeScript Record Type

A Comprehensive Guide to Understanding TypeScript Record Type

Joseph Gordon-Levitt
Release: 2025-02-08 11:03:10
Original
148 people have browsed it

A Comprehensive Guide to Understanding TypeScript Record Type

This guide explores TypeScript's Record type, a powerful tool for creating objects with consistent value types. We'll cover its definition, syntax, comparisons with tuples, practical applications like exhaustive case handling and enum mapping, and advanced uses with utility types like Partial, Pick, and Readonly.

Understanding the Record Type

The Record type lets you define object types where all values share the same type, while keys can vary. Its definition is:

Record<Keys, Type>
Copy after login
Copy after login
  • Keys: A union of string literals or a type derived from a union, defining the possible keys.
  • Type: The type of all values associated with the keys.

For example, Record<string, number> creates an object where every key is a string and every value is a number.

Record vs. Tuple

Both handle data collections, but differ significantly:

  • Record: Named properties with a fixed value type. Ideal for key-value mappings.
  • Tuple: Ordered list of elements, each potentially with a different type. Useful for fixed-size collections.

Example:

// Record: string keys, number values
type AgeMap = Record<string, number>;

// Tuple: string and number in specific order
type Person = [string, number];
Copy after login

Basic Record Usage

Defining a Record involves specifying key and value types:

// Object with string keys and string values
type User = Record<string, string>;
Copy after login

Practical Applications

  1. Exhaustive Case Handling: Ensure all cases of an enum or union are handled:

    enum Status { Pending, Completed, Failed }
    const statusMessages: Record<Status, string> = {
      [Status.Pending]: "Request pending...",
      [Status.Completed]: "Request complete!",
      [Status.Failed]: "Request failed."
    };
    Copy after login
  2. Generic Type Checking: Create reusable functions that generate Records:

    function createRecord<K extends string, T>(keys: K[], value: T): Record<K, T> {
      return keys.reduce((acc, key) => ({ ...acc, [key]: value }), {});
    }
    Copy after login
  3. Enum to Data Mapping: Create lookup tables from enums:

    enum Color { Red, Green, Blue }
    const colorHex: Record<Color, string> = {
    };
    Copy after login
  4. Lookup Tables: Efficiently map keys to values:

    type CountryCode = "US" | "CA";
    interface CountryInfo { name: string; }
    const countries: Record<CountryCode, CountryInfo> = {
      US: { name: "United States" },
      CA: { name: "Canada" }
    };
    Copy after login

Iterating Over Record Types

Several methods allow iteration:

  • Object.entries(): Iterates over key-value pairs.
  • for...in: Iterates over keys.
  • Object.keys(): Returns an array of keys.
  • Object.values(): Returns an array of values.

Advanced Usage with Utility Types

Combining Record with other utility types enhances its capabilities:

  • Pick: Selects specific properties:

    type Product = { name: string; price: number; description: string };
    type ShortProduct = Pick<Product, "name" | "price">;
    Copy after login
  • Readonly: Creates immutable objects:

    type ImmutableProduct = Readonly<Product>;
    Copy after login
  • Partial: Makes properties optional:

    Record<Keys, Type>
    Copy after login
    Copy after login
  • Nested Records: Create complex hierarchical data structures.

  • Conclusion

    The Record type is a valuable asset in TypeScript, offering a concise and type-safe way to manage objects with consistent value types. Its flexibility, combined with other utility types, allows for the creation of robust and maintainable code. For further exploration, consult the official TypeScript documentation and other resources.

    The above is the detailed content of A Comprehensive Guide to Understanding TypeScript Record Type. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template