What You'll Learn
You'll learn how to use Record with specific string literal types (not just string) to create strongly typed objects where every required key is known and typed at compile time.
Core Idea
So far, you've seen Record<string, T> to create objects with unknown string keys, all having the same value type. But what if you know exactly which keys your object should have?
You can pass a string literal union as the first type parameter to Record, locking in the exact set of allowed keys:
type Status = "pending" | "approved" | "rejected";
type StatusMessages = Record<Status, string>;
const messages: StatusMessages = {
pending: "Awaiting review",
approved: "All clear!",
rejected: "Try again"
};
TypeScript enforces that all three keys must be present and typed correctly. Missing one? Compile error. Extra key? Also an error (thanks to excess property checks).
When It's Useful
This pattern shines when:
- You have a fixed set of keys (like configuration options or state machine transitions)
- Every key needs to map to the same type of value
- You want exhaustiveness checking: all keys must be present
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
type MethodHandlers = Record<HttpMethod, () => void>;
const handlers: MethodHandlers = {
GET: () => console.log("Fetching..."),
POST: () => console.log("Creating..."),
PUT: () => console.log("Updating..."),
DELETE: () => console.log("Deleting...")
};
If you forget a method or add an extra one, TypeScript catches it immediately.
Key Takeaway: Use Record<StringLiteralUnion, T> to create type-safe objects with a known, fixed set of required keys—perfect for mappings, state tables, and configuration objects.