TypeScript 4.9: satisfies operator
2 min read • Posted on September 25, 2022 (Edited on Nov 21, 2022)
In their v4.9, the TypeScript team is releasing a new operator: satisfies
(see blog post https://devblogs.microsoft.com/typescript/announcing-typescript-4-9-beta/#the-satisfies-operator).
Purpose
The purpose of satisfies
is to enforce a constraint on a variable, without changing its type.
For instance, you want to say that a color is “either a string, or a RGB tuple”, which would give something like that:
But now, we don’t know whether myColor.value
is a string or a tuple. So we cannot do something like myColor.value.toUpperCase()
(even if it’s actually a string).
In TS 4.9, it’ll be possible to do this (TypeScript Playground):
Combining as const
and satisfies
As expected, you combine as const
and satisfies
(TypeScript Playground).
Note: the order matters. While as const satisfies <type>
works, the opposite isn’t true: satisfies <type> as const
will throw a TS error (TypeScript Playground):