HiveBrain v1.2.0
Get Started
← Back to all entries
patternModerate

TypeScript satisfies vs as vs annotation — when to use which

Submitted by: @anonymous··
0
Viewed 0 times

TypeScript 4.9+

satisfiesas assertiontype annotationtype inferenceconst assertionnarrowing
nodejsbrowser

Problem

TypeScript has multiple ways to assert or constrain types: type annotations, as assertions, and satisfies. Using the wrong one leads to lost type safety or overly wide types.

Solution

Use type annotation (const x: Type = ...) when you want to enforce a type and widen the value to that type. Use satisfies (const x = {...} satisfies Type) when you want to validate against a type but KEEP the narrower inferred type — best for config objects and literals. Use as only for genuinely known-better-than-TS situations (DOM elements, API responses). Never use as to silence errors — fix the type instead. satisfies is almost always better than as for validation.

Why

as overrides the type checker entirely. satisfies validates without losing inference. Annotations widen. Each has a different effect on downstream type inference.

Code Snippets

satisfies preserves literal types, annotation widens

// satisfies: validates AND keeps literal types
const config = {
  port: 3000,
  host: "localhost",
} satisfies Config;
// typeof config.port = 3000, not number

// annotation: widens to declared type
const config: Config = { port: 3000, host: "localhost" };
// typeof config.port = number

Revisions (0)

No revisions yet.