Using as const for Configuration Objects
You'll learn: How to use as const to lock down configuration objects with type-safe literal keys and values, preventing accidental modifications and enabling precise autocomplete.
The Configuration Object Challenge
Configuration objects are everywhere in TypeScript applications—API endpoints, theme settings, feature flags, route definitions. Without as const, these objects get widened to general types, losing the specificity that makes them useful as configuration:
const colors = {
primary: "blue",
secondary: "green"
};
// Type inferred as: { primary: string; secondary: string }
That string type is too loose. If you later check if (color === "blue"), TypeScript won't help you because it thinks color could be any string.
The as const Solution
Add as const to your configuration object to preserve exact literal values:
const colors = {
primary: "blue",
secondary: "green"
} as const;
// Type: { readonly primary: "blue"; readonly secondary: "green" }
Now TypeScript knows colors.primary is specifically "blue", not just some string. This enables:
- Exhaustive checking when switching on config values
- Precise autocomplete for allowed values
- Type-safe lookups using config keys
- Compile-time errors if you typo a config value
Real-World Example
const API_ENDPOINTS = {
users: "/api/users",
posts: "/api/posts",
auth: "/api/auth"
} as const;
function fetchData(endpoint: typeof API_ENDPOINTS[keyof typeof API_ENDPOINTS]) {
// endpoint type: "/api/users" | "/api/posts" | "/api/auth"
// Not just: string
}
fetchData(API_ENDPOINTS.users); // ✓
fetchData("/api/wrong"); // ✗ Error!
Key Takeaway: Use as const on configuration objects to preserve literal string and number values, creating a single source of truth that TypeScript can validate throughout your codebase.