DEV Community

Lautaro Suarez
Lautaro Suarez

Posted on

"Satisfies" operator, Typescript

Introduction

On this post i will show a simple example on how to use satisfies and when should you use it. Do not hesitate to ask me anything.

What is the "satisfies" operator?

The satisfies operator checks if a given type satisfies a specific condition or interface, it will ensure that all variables fit the definition and have all the required properties of a specific type or interface.

Why is it useful?

It is useful cause we can use it when for instance we defined a type with two possibles values and then it does not know which one is the one being use. It will help us achieve a more accurate way of knowing what is the actual type of an specific value.
Let's see an example:

type allMyInfo = personalInfo | workInfo 
Enter fullscreen mode Exit fullscreen mode

We can see that allMyInfo will be either personalInfo or workInfo.

type personalInfo = "Mike" | "Allan" | "Suarez";
type workInfo = {
  id: number;
  bossAge: number;
};
Enter fullscreen mode Exit fullscreen mode

After defining the two type that allMyInfo is using we are going to define a Person type that will have two values and both of them will have allMyInfo since it could have any of them.

type Person = {
  myInfo: allMyInfo;
  myOtherInfo: allMyInfo;
};
Enter fullscreen mode Exit fullscreen mode
const applicant: Person = {
  myInfo: "John",
  myOtherInfo: { id: 123, bossAge: 28 },
};
Enter fullscreen mode Exit fullscreen mode

Now let's try to access any method such as "toUpperCase" it will show an error saying something like "Property 'toUpperCase' does not exist on type" ,etc.

applicant.myInfo.toUpperCase();
Enter fullscreen mode Exit fullscreen mode

This error occurs because TypeScript is unsure whether the value of "myInfo" or "myOtherInfo".

We can fix this error doing an if statement and checking if in this case "myInfo" is of type string and inside it put the method toUpperCase.

However thats when our satisfies friend comes.

const applicant = {
  myInfo: "John",
  myOtherInfo: { id: 123, age: 22 },
} satisfies Person;
Enter fullscreen mode Exit fullscreen mode

Adding the satisfies at the end with the type will let us in this case use the method since now it knows which value should choice bwtween the options given before.

Conclusion

I hope someone found it useful and in case of having any questions ask them, im coming from vacation so my writing is probably a little rusty, u can judge me ;).

Top comments (0)