By Tomer Erusalimsky
January 14, 2025 • 1 min read
The as const
assertion is a small feature with big benefits. Here's how it can improve your TypeScript code:
const color = "blue"; // type: string const color = "blue" as const; // type: "blue"
✅ Get precise literal types instead of broad generic types
const roles = ["admin", "user"] as const; // type: readonly ["admin", "user"]
✅ Create read-only data structures that TypeScript can reason about
const statuses = { SUCCESS: "success", ERROR: "error", } as const; type Status = typeof statuses[keyof typeof statuses]; // type: "success" | "error"
✅ Build type-safe enums and union types from objects
By narrowing types, as const
helps TypeScript provide smarter suggestions and catch bugs earlier.
💡 Use as const
when you want precise, read-only, and narrow types. It's especially handy for:
The as const
assertion is a powerful tool for creating more robust and type-safe TypeScript applications with minimal effort.