Type constraints

The satisfies keyword ensures that a value matches a specified type without changing the value's inferred type. Unlike as, it does not assert a type, but rather validates that some data matches a particular type during compilation.

The satisfies operator was added to TypeScript in version 4.9. If your TypeScript compiler does not recognize it, you are likely running an outdated version.

Parameter contravariance

In type theory, contravariance means you can substitute a parameter type with a more general type (called a super type). For example, a function that accepts string | number can be safely substituted for one that only accepts string.

We can use satisfies to check contravariant function types, such as the function valueChecker which can be constrained to a StringChecker type.

The parameter value can either be string or number in valueChecker, but also satisfies the more specific function type of StringChecker. This is called parameter contravariance.

The inverse of this is called parameter covariance, where a parameter type can be substituted for a more specific type. TypeScript does allow parameter covariance, and will produce an error for the example below.

Applying to constants

Definitions of static data with as const can be augmented with the satisfies keyword to type check the constant value.

Loading TypeScript...

Was this page helpful?