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>
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];
Basic Record
Usage
Defining a Record
involves specifying key and value types:
// Object with string keys and string values type User = Record<string, string>;
Practical Applications
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." };
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 }), {}); }
Enum to Data Mapping: Create lookup tables from enums:
enum Color { Red, Green, Blue } const colorHex: Record<Color, string> = { };
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" } };
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">;
Readonly
: Creates immutable objects:
type ImmutableProduct = Readonly<Product>;
Partial
: Makes properties optional:
Record<Keys, Type>
Nested Record
s: 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!