TypeScript2 min read
TypeScript: as const Changes Everything
Make your arrays and objects readonly with literal types
S
Shahar Amir
TypeScript: as const Changes Everything
What type is this?
typescript
12
const colors = ["red", "green", "blue"];// Type: string[]TypeScript widens it to string[]. But what if you want the exact values?
Enter as const
typescript
12
const colors = ["red", "green", "blue"] as const;// Type: readonly ["red", "green", "blue"]Now TypeScript knows the exact values.
Why This Matters
typescript
1234567
// Without as constconst status = ["pending", "active", "done"];type Status = typeof status[number]; // string 😕
// With as constconst status = ["pending", "active", "done"] as const;type Status = typeof status[number]; // "pending" | "active" | "done" 🎉You get a union type automatically!
Works With Objects Too
typescript
123456789
const config = { api: "https://api.example.com", timeout: 5000,} as const;
// Type: {// readonly api: "https://api.example.com";// readonly timeout: 5000;// }Real-World Example
typescript
123456789101112131415
const ROUTES = { home: "/", about: "/about", blog: "/blog",} as const;
type Route = typeof ROUTES[keyof typeof ROUTES];// Type: "/" | "/about" | "/blog"
function navigate(route: Route) { // Only accepts valid routes!}
navigate(ROUTES.home); // ✅navigate("/random"); // ❌ Error!Key Benefits
- Literal types instead of widened primitives
- Readonly - prevents accidental mutations
- Union types from arrays automatically
- Type-safe constants
Stop defining union types manually. Let as const do the work.
#types#const#readonly
Stay Updated 📬
Get the latest tips and tutorials delivered to your inbox. No spam, unsubscribe anytime.