DEV Community

Cover image for Unlocking Literal Types in TypeScript with "as const"
Arka Chakraborty
Arka Chakraborty

Posted on

Unlocking Literal Types in TypeScript with "as const"

Deep Dive into as const


Ever declared a constant in TypeScript and wondered why its type widened to stringinstead 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" vs string).
  • 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

Enter fullscreen mode Exit fullscreen mode

💡With as const

// With as const
const color = "blue" as const;
type Color = typeof color; 
// type is "blue"

Enter fullscreen mode Exit fullscreen mode

💡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>;
}

Enter fullscreen mode Exit fullscreen mode

Config Objects

const theme = {
  mode: "dark",
  accent: "blue",
} as const;

// Types are "dark" | "blue", not string

Enter fullscreen mode Exit fullscreen mode

💡Remember: as const is for values, not type definitions.

Top comments (0)