Deep Dive into as const
Ever declared a constant in TypeScript and wondered why its type widened to string
instead of "blue"
? That’s where as const
comes in.
💡Context
By default, TypeScript widens literal values. This can make union types and prop definitions less strict. The as const
assertion prevents widening, preserving exact literal types and making objects/arrays readonly
at the value level.
💡Intro
In React projects, as const
is handy for config objects, tuple-like arrays, and state actions. It enforces immutability while improving type safety.
💡Why Use This?
- Prevents type widening (
"blue"
vsstring
). - Makes arrays/objects deeply readonly.
- Critical for discriminated unions.
💡Without as const
// Without as const
const color = "blue";
type Color = typeof color;
// type is string
💡With as const
// With as const
const color = "blue" as const;
type Color = typeof color;
// type is "blue"
💡Real Life Use Cases
Component Props
const buttonVariants = ["primary", "secondary"] as const;
type Variant = typeof buttonVariants[number];
type ButtonProps = { variant: Variant };
function Button({ variant }: ButtonProps) {
return <button>{variant}</button>;
}
Config Objects
const theme = {
mode: "dark",
accent: "blue",
} as const;
// Types are "dark" | "blue", not string
💡Remember: as const
is for values, not type definitions.
Top comments (0)