Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 96 ยท Modern Features

The satisfies Operator

Learn the TypeScript satisfies operator - validate objects against a type without losing their precise inferred types, and when to choose it over annotations or as.

Most of the time you give a value a type in one of two ways: you annotate it (const x: Config = ...) or you let TypeScript infer it. Both have a cost. An annotation checks the value, but afterwards TypeScript only remembers the annotated type and forgets everything specific about the value. Inference remembers every detail, but nothing checks that the value has the shape you meant.

The satisfies operator, added in TypeScript 4.9, gives you both. value satisfies Type checks that the value fits Type, reports typos and missing properties just like an annotation would, and then keeps the value's own inferred type. It's a small keyword with a big effect on configuration objects, lookup tables and anything you write once and read many times.

This lesson builds on type inference, literal types and as const and type assertions, so skim those first if the terms are new.

The problem: annotations forget details

Imagine a theme where each color is either a hex string or an RGB tuple. A Record type describes that nicely, and annotating the object catches mistakes. But look what happens when you use one of the colors:

TypeScript An annotation widens every property (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

This program doesn't run. The compiler stops with two errors:

TEXT
main.ts(12,27): error TS2339: Property 'toUpperCase' does not exist on type 'Color'.
  Property 'toUpperCase' does not exist on type 'Rgb'.
main.ts(13,26): error TS2339: Property 'join' does not exist on type 'Color'.
  Property 'join' does not exist on type 'string'.

The annotation did its job: it would have caught a misspelled key or a number where a color belongs. But it also replaced the type of every property with the declared Color. Whether primary started life as a string no longer matters; from now on it's "a string or a tuple", and you'd need a narrowing check before every use.

Removing the annotation fixes the reading side, since inference sees primary: string and accent: number[]. But then nothing stops you from writing primray or forgetting text.

satisfies: check, then keep the inferred type

Write the type after the value with satisfies, and you get the check without the widening:

TypeScript The same theme with satisfies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
#3B82F6
236, 72, 153
r=236 g=72 b=153

Hover over theme in a real editor and you'd see:

TypeScript
const theme: {
  primary: string;
  accent: [number, number, number];
  text: string;
};

Two things happened. First, TypeScript checked the object against Record<ThemeKey, Color>. Second, the type it inferred for theme is the object's own type, property by property. Notice that accent became a tuple [number, number, number] rather than number[]: the type after satisfies also acts as a contextual type, guiding inference the same way a parameter type guides an arrow function's parameters (see function types).

The expression x satisfies T has the type of x, not T. That's the whole idea.

What satisfies catches

Because satisfies performs the same check as an annotation, you keep all the safety. Here the key accent is misspelled:

TypeScript A typo in a key is still caught (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The compiler even suggests the fix:

TEXT
main.ts(6,3): error TS2561: Object literal may only specify known properties, but 'acent' does not exist in type 'Record<ThemeKey, Color>'. Did you mean to write 'accent'?

Fix the spelling and try two more mistakes in the editor. Change the text value to 42 and you get error TS2322: Type 'number' is not assignable to type 'Color'. Delete a whole line, and you get TS2741: "Property '...' is missing in type ... but required in type ...". TypeScript tends to report an unknown key first and other problems once it's fixed, which is why you sometimes fix errors in rounds.

So satisfies gives you:

  • excess property checks on object literals (typos in keys),
  • missing property checks (required keys you forgot),
  • value checks for every property.

satisfies vs annotation vs as

There are now three ways to "put a type on" a value. They are not interchangeable:

Syntax Checks the value? Resulting type Use it when
const x: T = value Yes T (details are lost) You want the variable to be a T, e.g. it will be reassigned or passed around as T.
const x = value satisfies T Yes The value's own inferred type You want a check, but you'll read specific properties later.
const x = value as T Barely (only that the types overlap) T You know something the compiler can't, e.g. data from a trusted source. Use rarely.

The danger with as is that it's an assertion, not a check. It happily accepts an object that's missing properties:

TypeScript as hides a missing property, satisfies does not

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output shows the lie that as told:

TEXT
asserted port: undefined
undefined
checked port: 8080

TypeScript believes asserted.port is a number, yet at runtime it's undefined. If you uncomment the satisfies line with the missing port, the program won't compile: "Property 'port' is missing in type '{ host: string; }' but required in type 'ServerConfig'."

A good rule of thumb: reach for satisfies first when you write a literal value, an annotation when you declare what a variable is, and as only as a last resort.

When an annotation is the better choice

satisfies keeps the narrow type, and sometimes narrow is exactly what you don't want. If a variable will be reassigned, or you want callers to depend only on the declared contract, annotate:

TypeScript
interface Settings {
  volume: number;
  mode: 'light' | 'dark';
}

let current: Settings = { volume: 5, mode: 'light' };
current = { volume: 7, mode: 'dark' }; // fine: current is a Settings

let draft = { volume: 5, mode: 'light' } satisfies Settings;
// draft.mode has type 'light' here, so this would fail:
// draft = { volume: 7, mode: 'dark' };

The commented line fails because draft's inferred type is { volume: number; mode: "light" }. The next section explains why mode stayed a literal.

Literal types survive

When the type after satisfies contains literal types, TypeScript keeps the literal it sees instead of widening it to string or number. You can prove it with the small Equal checker from utility types: a line like type _t = Expect<Equal<A, B>> only compiles when A and B are the same type.

TypeScript Proving which types satisfies keeps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints All type checks passed: { mode: 'dark', size: 14 }, which means all four type assertions compiled:

  • the annotation gave annotated exactly the declared type,
  • satisfies kept mode as the literal 'dark' (because Mode is a literal union) but widened size to number (because the target says number),
  • without any type, mode widened to string, which would no longer fit a Mode parameter.

That middle case is often what you want: you can pass satisfied.mode to a function that takes a Mode without a cast.

satisfies with as const

satisfies keeps literal types only where the target type asks for them. Add as const and every value becomes a readonly literal, while satisfies still checks the shape. The combination is written as const satisfies T, in that order:

TypeScript as const satisfies for a lookup table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
listUsers: GET /users
createUser: POST /users (login required)
deleteUser: DELETE /users/:id (login required)
POST

Look at what you got for free:

  • EndpointName is "listUsers" | "createUser" | "deleteUser". With an annotation of Record<string, Endpoint>, keyof would just be string, and describe('lisUsers') would compile. Here a typo is an error.
  • CreateMethod is exactly "POST".
  • Every entry was still checked: a path without a leading slash, or method: 'PATCH', would fail to compile because of the template literal type and the Method union.

The Object.keys(...) as EndpointName[] assertion is needed because Object.keys always returns string[] (objects can have extra keys at runtime). For a table you wrote yourself, that assertion is safe.

The order matters: as const satisfies T works, but satisfies T as const is a syntax error, because as const may only follow a literal. Read it as "make this constant, then check it".

Real-world uses

Configuration files

Many tools export a configuration object. With satisfies, the file gets autocompletion and type checks while the exported value keeps its precise type:

TypeScript
// vite.config.ts (read-only example)
import type { UserConfig } from 'vite';

export default {
  server: { port: 5173 },
  build: { outDir: 'dist', sourcemap: true },
} satisfies UserConfig;

Some frameworks provide a defineConfig() helper that does the same job through a generic function; satisfies gives you the effect without a helper.

Typing a function by its signature

satisfies also works on function expressions. The target type gives the parameters their types (contextual typing), and the function keeps its own, possibly narrower, return type:

TypeScript Contextually typed handlers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is HELLO, GBH and undefined. Without satisfies, the input parameters would be implicitly any and strict mode would reject them (TS7006). With an annotation, handlers.shout('hello') would be typed string | undefined, and the loud: string line would fail.

(The w[0] inside initials has type string because our editor doesn't enable noUncheckedIndexedAccess; with it, the type would be string | undefined, which join accepts anyway.)

Limits and gotchas

  • The variable is still mutable. satisfies doesn't make anything readonly. Without as const, properties of a const object can still be changed, and their types are the widened ones (string, number) unless the target type had literals.
  • Excess property checks only apply to literals. existingObject satisfies T checks assignability, like passing a variable to a function, so extra properties on a variable are allowed. See type compatibility.
  • It's purely compile-time. satisfies is erased from the JavaScript output, so it costs nothing at runtime and validates nothing at runtime. Data from outside your program still needs runtime validation.
  • It's not a replacement for parameter types. Function parameters and return types are still best annotated directly.
  • Error codes differ slightly. When the value isn't assignable at all, the error is TS1360: "Type '...' does not satisfy the expected type '...'." Property-level problems use the usual TS2322, TS2353 or TS2741.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of x in const x = { size: 10 } satisfies { size: number | string };?

    satisfies keeps the inferred type of the value. The target has no literal types, so 10 widens to number, giving { size: number }.
  2. 2. Which of these catches a misspelled key in an object literal?

    Annotations and satisfies both run excess property checks on object literals. An as assertion only checks that the types overlap, so it misses many mistakes.
  3. 3. Does const p = { host: "a" } as { host: string; port: number }; compile?

    The types overlap, so the assertion is allowed. The compiler trusts you, but the object never had a port property, so it is undefined at runtime.
  4. 4. Given const table = {...} as const satisfies Record<string, Item>;, what is keyof typeof table?

    The variable keeps the object's own inferred type, so keyof gives the real keys. With an annotation of Record<string, Item> it would only be string.
  5. 5. Which statement about satisfies is true?

    Like every type-level syntax, satisfies is erased from the output. It works on any expression, does not add readonly, and does nothing at runtime.

Summary

  • value satisfies Type checks the value against Type but the expression keeps the value's own inferred type.
  • It catches the same mistakes as an annotation: unknown keys, missing keys and wrong value types.
  • The target type is also a contextual type: it turns arrays into tuples, keeps literals where the target has literal types and gives function parameters their types.
  • Use an annotation when the variable should be that type (reassignment, public contracts), satisfies for values you read precisely later, and as only when you truly know better than the compiler.
  • as const satisfies T makes a readonly, fully literal value that is still checked, perfect for lookup tables and deriving types with keyof typeof.
  • satisfies is compile-time only; validate outside data at runtime.

Next: What's New in TypeScript 5.x, 6.0 and 7.0