Advanced TypeScript

`satisfies`, `as const` & Literal Types

Literal types preserve exact values. as const freezes inference to readonly literal shapes. satisfies checks a value against a target type without widening away its precise inferred type.
  • Literal types represent exact values
  • as const preserves literals deeply
  • satisfies checks without replacing inference
  • This is ideal for configuration objects
  • as Type is not the same
`satisfies` keeps exact keys
type Route = { path: string; auth: boolean }

const routes = {
  home: { path: "/", auth: false },
  admin: { path: "/admin", auth: true },
} satisfies Record<string, Route>

type RouteName = keyof typeof routes
// "home" | "admin"
The object is checked as a route map, but its exact keys are preserved.
`as const` for literal arrays
const statuses = ["idle", "loading", "success", "error"] as const

type Status = typeof statuses[number]
// "idle" | "loading" | "success" | "error"
`as const` turns a normal string array into a source of literal union types.
Literal-preserving tools
ToolWhat it doesUse for
literal typeExact value typeVariants and constants
as constReadonly literal inferenceArrays/config values
satisfiesCheck shape, keep inferenceConfig maps
as TypeForce compiler beliefLast resort / interop
Sources
  • TypeScript Release Notessatisfies operator and const inference
  • The TypeScript HandbookLiteral Types
  • Effective TypeScript, 2nd EditionType inference