[TypeScript 4.9] What the new ‘satisfies’ operator makes possible.
I encountered the new satisfies
operator while upgrading the Storybook version from 6 to 7 and reading this part of Storybook7 documentation, which kindly explains what this operator can do for us.
Basically, this satisfies
operator offers a safe upcast of keys and values of an object.
Let’s dive into what is now possible with this fresh and impressive feature of TypeScript 4.9 with easy & simple examples.
Let’s say we have an object called a palette
as below.
Obviously, we can use array methods on palette.red
as it’s inferred as number[]
We also can use string methods on palette.green
, which is inferred as string
.
Not so bad, but actually, as some of you might notice, we made a typo( glue instead of blue) and there was no alert suggesting there might be a typo.
To prevent any unexpected typos, we can try declaring types to type keys and values of the object.
Here, the object palette
is typed, keys to be Colors
, and values to be string | RGB
. And now we can see get the alert we wanted that helps prevent future bugs.
However, we now encounter an undesirable error because TypeScript (before v4.9) had been not smart enough to specify whether palette.green
is string
or RGB
.
Can’t we just validate the keys and the values of the object palette in TypeScript?
With the satisfies
operator, yes we can!
Let’s move Record<Colors, string | RGB>
after the object literal and put satisfies
operator between the object literal and the Record type as below.
Now, the typo alert is still available and each method is accessible thanks to the appropriate type inference.
Even if we type the values of the object palette as unknown, the type information of palette.red
and palette.green
is maintained, making it possible to use array or string methods, respectively.
To sum up, the satisfies
operator allows us to enjoy enhanced type safety of keys and values of an object in TypeScript.