Typescript — The satisfies
Operator
Hi all,
Yesterday I found a new way in Typescript to ensure the type-safety better in the code. Let’s check what is it and how to do it!
We are going to see new satisfies
operator, released in TypeScript 4.9.
Let’s check the following code :
We have city, it can be eitherCityName
orCityCoordinates
type City = CityName | CityCoordinates;
CityName is string which respresents any cities,
//another type CityName
type CityName = "Colombo" | "Jaffna" | "Galle";
//CityCoordinates represents coordinates of a city
type CityCoordinates = {
x: number;
y: number;
};
And the Person
type has placeOfBirth
and currentPlace
, both of which are of type City
//the Person type has placeOfBirth and currentPlace, both of which are of type City:
type Person = {
placeOfBirth: City;
currentPlace: City;
};
Now we want to create a new variable person and use Person type.
const person:Person = {
placeOfBirth: "Colombo",
currentPlace: { x: 6, y: 3 },
}
Here come the issue, let’s imagine that you have a new requirement to make the placeOfBirth to capitalise. So what we will do is, use toUpperCase() right? Ok let’s try that in the Typescript Playground.
What happened above ? placeOfBirth
is a type of CityName
which can be either string or or object with numbers. Till Typescript 4.8 , Typescript cannot solve this issue.
HERE COMES SATISFIES KEYWORD
let’s use the satisfies keyword ,the syntax as follows:
const person1= {
placeOfBirth: "Colombo",
currentPlace: { x: 6, y: 3 },
} satisfies Person
let’s now try to console log the person1,
const person1= {
placeOfBirth: "Colombo",
currentPlace: { x: 6.2121, y: 3 },
} satisfies Person
console.log(person1.placeOfBirth.toUpperCase());
//OUTPUT-> COLOMBO
console.log(person1.currentPlace.x.toFixed(2));
//OUTPUT-> 6.21
In conclusion, with satisfies
we can use in two different places. Type safety saves us from runtime errors and powerful type inference gives us most specific types for free.
Thank you for reading !