TypeScript
The satisfies operator
The satisfies
operator introduced in TypeScript 4.9 allows you to validate whether a value matches a specific type without losing the type inference.
This can be useful for configuration objects with optional properties or properties where the value can be of multiple types.
In the following example the type of configuration
will be Config
. However it is not necessary to check whether port is defined and of type number
later on, because of type inference.
type Config = {
host: string
port?: string | number
}
const configuration = {
host: true,
port: 8080,
} satisfies Config
// The type of `configuration.port` is inferred and will be `number`
console.log(typeof configuration.port)
Prefer using satisfies
over as Type
, because as Type
forces TypeScript to treat a value as a type even though it might not match. Potentially causing runtime errors.
See TypeScript documentation for more information.