4 min read
•Question 15 of 48mediumWhat is the Record utility type?
Creating object types with Record.
What You'll Learn
- Record<K, V> utility
- Common use cases
- Comparison with index signatures
Record<K, V>
Creates an object type with keys of type K and values of type V.
code.tsTypeScript
// Simple record
type Scores = Record<string, number>;
const scores: Scores = {
alice: 95,
bob: 87,
charlie: 92
};With Union Types
code.tsTypeScript
type Status = "pending" | "approved" | "rejected";
type StatusColors = Record<Status, string>;
const colors: StatusColors = {
pending: "yellow",
approved: "green",
rejected: "red"
};Complex Values
code.tsTypeScript
interface User {
name: string;
email: string;
}
type UserMap = Record<string, User>;
const users: UserMap = {
u1: { name: "John", email: "john@example.com" },
u2: { name: "Jane", email: "jane@example.com" }
};Record vs Index Signature
code.tsTypeScript
// Index signature
interface Obj1 {
[key: string]: number;
}
// Record (equivalent)
type Obj2 = Record<string, number>;
// Record is more concise and works with union keys