Verify if some literal value satisfies a given type

Kamran Ahmed
InstructorKamran Ahmed
Share this video with your friends

Social Share Links

Send Tweet
Published 6 months ago
Updated 2 months ago

In this lesson you will learn how to verify if some literal value satisfies any given type or not. There are two ways to do this i.e. either by declaring a variable of some given type and assigning it the value or we can use the satisfies keyword. We will take an example and look at both of the ways in this video.

[00:00] Here we have a dummy write file function, which accepts the file name and the JSON content that it needs to write to that file, and then we're calling this function and passing this object literal as JSON to write it to this file. Now let's say that we want to verify if if this object literal matches this user type or not. There are 2 ways to do this. The first one is that we take the object literal [00:20] from here, and we use a user variable instead, and then the user variable could be of user type, and we put the value here. And now if we try to put the wrong data into our file, we will get the error from TypeScript. The other way to do this without declaring a separate variable is using the satisfies keyword. So if you go back to the old code snippet, we can simply [00:39] write satisfies, and we give it the user type here. And now it will make sure that this literal satisfies the user type. So if we try and pass the wrong data here, we'll get the same error that location cannot be a number. And if we pass the correct value as per the type, the error is gone.