CodePark/ questions / Functions & satisfies
START PRACTICINGPRACTICE
Frontend question · TypeScript › Functions & satisfies

Compare a type annotation, the satisfies operator and an as assertion.

type Theme = Record<string, string>;

const a: Theme = { primary: "#09f" };            // type is Theme
const b = { primary: "#09f" } satisfies Theme;   // type is { primary: string }
const c = { primary: 123 } as unknown as Theme;  // no error, just wrong

An annotation checks the value and gives the variable the declared type. satisfies checks the value but keeps the exact inferred type. as does not really check at all.

Annotation (const a: Theme): TypeScript checks the value against the type, then makes the variable that type. You lose the more specific inferred type. So a.primary and a.anything are both just string.

satisfies (added in TypeScript 4.9): TypeScript checks the value against the type but keeps the inferred type. You still get validation, including excess property checks. But b still knows it has exactly primary, so b.secondary is an error.

as assertion: TypeScript does not validate the value. It just treats the value as that type. It only refuses when the two types are clearly unrelated, and as unknown as gets around even that. Use it rarely, only when you really know more than the compiler.

  • An annotation checks the value and gives the variable the declared, wider type.
  • satisfies checks the value but keeps the exact inferred type.
  • as does no real validation. It overrides the compiler.
  • Prefer an annotation or satisfies. Use as only as an escape hatch.