~/alexsh.blog

$ cat advanced-typescript/02-satisfies-operator-and-const-assertions.md

satisfies Operator and const Assertions

February 9, 20261 min readpart 02/20

Difficulty: Upper Intermediate. Prerequisites: Type inference, literal types, readonly types.

The satisfies operator (TS 4.9+) and as const assertions are essential modern TypeScript tools. While as const creates the narrowest possible literal type, satisfies validates against a type without widening. Together they enable precise typing of configuration objects while preserving full literal type information.

Key concepts

  • as const creates deeply readonly types with literal values
  • satisfies checks type compatibility without changing the inferred type
  • Combining both for validated literal configurations
  • Preserving string literal keys while ensuring value types
  • Type-safe exhaustive objects with known keys

Example

codets
// WITHOUT satisfies - type annotation widens
const colors1: Record<string, [number, number, number]> = {
  red: [255, 0, 0], green: [0, 255, 0],
};
colors1.typo; // No error - any string key allowed!

// WITH satisfies - validates but preserves literal types
const colors2 = {
  red: [255, 0, 0], green: [0, 255, 0],
} satisfies Record<string, [number, number, number]>;
colors2.red;   // Type is [number, number, number] — keys 'red'|'green' preserved!
colors2.typo;  // Error! Only 'red' | 'green' allowed

// as const for deepest literal type
const routes = { home: '/', users: '/users' } as const;
type RouteValues = typeof routes[keyof typeof routes]; // '/' | '/users'

// COMBINING BOTH for ultimate control
const apiRoutes = {
  getUsers: '/api/users',
  getUser: '/api/users/:id',
} as const satisfies Record<string, `/${string}`>;
// Validates AND preserves literal types!

// Real-world: Drizzle ORM — defineConfig({ dialect: "postgresql" }) satisfies Config

Resources

Practice

Hints

  • Try using "as const" first to see how it narrows types, then add "satisfies" to add validation without losing the narrow types.
  • Remember: "satisfies" validates at the type level but doesn't change the inferred type.