DEV Community

Cover image for A Deep Dive into the satisfies operator in Typescript

A Deep Dive into the satisfies operator in Typescript

Maina Wycliffe on March 12, 2024

In Typescript version 4.9, Typescript introduced the satisfies operator. Over the last few months, I have seen examples of it being used out in the...
Collapse
 
fyodorio profile image
Fyodor

That’s really awesome. The only problem is that we’ve got another way of creating debugging nightmares with this new approach 😅 imo, that’s the main issue with JS/TS — so many ways to implement [practically] the same stuff.

Collapse
 
brense profile image
Rense Bakker

Debugging nightmares because of satisfies operator? Please elaborate? Satisfies allows you to use a narrower type, which is better for debugging last time I checked?

Collapse
 
fyodorio profile image
Fyodor

Yes, edge cases in obscure type inference is one of the major sources of time-eating debuggin in larger TS apps. For simple cases that's quite straightforward, of course, I agree with you here.

Collapse
 
brense profile image
Rense Bakker

Great explanation of satisfies operator! Dev.to needs more of this! 👍

Collapse
 
mainawycliffe profile image
Maina Wycliffe

Thank you 🙏

Collapse
 
anodynos profile image
Angelos Pikoulas • Edited

What is the benefit compared to const circle: Circle = {...} ? Or const helloStr: string = 'hello' and so on?

Collapse
 
mainawycliffe profile image
Maina Wycliffe

As explained, explicit type annotation ties the type of variable to the annotation, i.e. helloStr can now only be a string, instead of the narrower literal type "hello" and if you wanted to use it in a place that requires the type "hello" (not string), you would need to narrow it down to hello (by checking if it's hello before passing it along).

In contrast, when using satisfies, you get the same type-safety that helloStr can only be a string, but the inferred narrower type of hello is retained, hence we are just checking to make sure that our variable type fits a certain type (in this case can only a string) without changing its narrower or more precise inferred type. For const helloStr, the type hello is more precise and much a better type than string.

This is because you should always prefer the narrower variable type whenever possible (link).