The 'satisfies'-operator in TypeScript

Validate that the type of an expression matches some type, without changing the resulting type of that expression

TypeScript 4.9 satisfies

With version 4.9, TypeScript introduces a new operator called the “satisfies”-operator. It’s purpose is to make non-homogenous type sets more flexible by allowing a union of types to satisfy the overall type.

Fix type error with Record<>

The best example to demonstrate this new operator uses a “Record”-type, where the types of the values can differ.

type Keys = "alpha" | "beta" | "gamma";

const variants = {
  alpha: 0,
  beta: 1,
  gamma: "three"
} satisfies Record<Keys, string | number>;

// With the new 'satisfies'-operator,
// the types for each of the properties
// is correctly inferred.
const otherBeta = variants.beta + 10;
const gammeUppercase = variants.gamma.toUpperCase();

As you can see, the new code allows to correctly infer the valid type for the given key. This wouldn’t be possible before TypeScript 4.9. The compiler would complain that the value could be of type string or number, whereas now the compiler correctly infers the specific type.

Property Name Constraining

We can also use the new operator to instruct the compiler that’s it OK for a set to only include some given keys, but not accept any others.

type Keys = "alpha" | "beta" | "gamma";

const variants = {
    alpha: "value",
    beta: 0,
    // The compiler will show an error,
    // as 'delta' is not part of the keys.
    delta: new Date()
} satisfies Partial<Record<Keys, unknown>>;

More examples

For a complete list of examples with in-depth descriptions, I highly recommend this feature’s original issue on Github, where the author describes many use cases (link also in the addendum).

Suggestions

Related

Addendum

Languages