sometimes, you are working with some data
let's take an object
const palette = {
red: [255, 0, 0],
green: "#00ff00",
bleu: [0, 0, 255]
};
and you want that object to be a certain shape, enforce some kind of type safety
notice how I wrote bleu and not blue in the object?
one solution would be to create a variable, set the expected type to that variable, and then assign it a value
type Colors = "red" | "green" | "blue";
type RGB = [red: number, green: number, blue: number];
const palette: Record<Colors, string | RGB> = {
red: [255, 0, 0],
green: "#00ff00",
bleu: [0, 0, 255]
};
problem is, we now lost some information!
we used to know the green property was a string, and the other ones were tuples
now they all are string | [number, number, number]
so we lost information, and we don't want that
we needed a new way to enforce a certain shape, without actually assigning it to a object
and that is exactly what satisfies does
const palette = {
red: [255, 0, 0],
green: "#00ff00",
bleu: [0, 0, 255]
} satisfies Record<Colors, string | RGB>;
we can catch the typo, and we retain the fact the green property is a string and the other ones are tuples