In Typescript, the operator satisfies
is used as way to check whether a type satisfies an interface or a condition. satisfies
makes sure that the properties of a type that are required are met.
Examples
Suppose we want to create an object called newUser
which uses two types: Username
and Email
, which for this example will be limited to three possible values each, and before taking that newUser
object and submitting it to the database, we want to check to make sure that the newUser
object satisfies the requirement by using both types: Username
and Email
. Here’s how we would do that:
type Username = "auser" | "buser" | "cuser";
type Email = "[email protected]" | "[email protected]" | "[email protected]";
type UserInfo = {
id: number,
username: Username,
email: Email
};
const newUser = {
id: 123,
username: "auser",
email: "[email protected]"
} satisfies userInfo
In the above example, the Typescript compiler would have no issue with that example. Let’s try to change the value of the username
property in the newUser
object to a username that is different from the three available usernames:
type Username = "auser" | "buser" | "cuser";
type Email = "[email protected]" | "[email protected]" | "[email protected]";
type UserInfo = {
id: number,
username: Username,
email: Email
};
const newUser = {
id: 123,
username: "duser", //Type '"duser"' is not assignable to type 'Username'.
email: "[email protected]"
} satisfies userInfo
In this case the Typescript compiler gives us the above error and therefore the object does not satisfy the type userInfo
.
We can also use satisfies
along with a utility type. For example, if we want to exclude the property id
in the anotherUser
object, we would do the following:
const anotherUser = {
username: "auser",
email: "[email protected]"
} satisfies Omit<UserInfo, "id">
In the above example, the Typescript compiler would accept this without errors.