TypeScript

const Assertions for Literal Types

admin by @admin ADMIN
Jun 18, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`as const` freezes a value as deeply readonly and infers the narrowest possible literal types. Replaces enums for most use cases — better tree-shaking, no runtime cost.
TypeScript
Raw
// Without `as const`: type widens to string[]
const ROLES = ['admin', 'editor', 'viewer'];
type Role = typeof ROLES[number];   // string ❌

// With `as const`: type is the readonly tuple
const ROLES_C = ['admin', 'editor', 'viewer'] as const;
type RoleC = typeof ROLES_C[number]; // 'admin' | 'editor' | 'viewer' ✓

// Same trick for record-style config objects:
const COLORS = {
  primary:   '#3b82f6',
  danger:    '#ef4444',
  success:   '#10b981',
} as const;

type ColorName = keyof typeof COLORS;        // 'primary' | 'danger' | 'success'
type ColorHex  = typeof COLORS[ColorName];   // '#3b82f6' | '#ef4444' | '#10b981'
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.