TIL: `satisfies` is my favorite TypeScript keyword Sat, Dec 21, 2024 I鈥檝e been doing a lot of work in TypeScript lately, and with that I鈥檝e spent quite a bit of time learning more about its type system. TypeScript is a wonderfully advanced language though it has an unfortunately steep learning curve; in many ways it鈥檚 the complete opposite of Go. One confusing thing about TypeScript is that it doesn鈥檛 always infer the most precise type possible. As an example: // name is of type "Jerred" const name = "Jerred"; // person1 is of type { name: string } const person1 = { name: "Jerred", }; // person2 is of type { readonly name: "Jerred" } const person2 = { name: "Jerred", } as const; Why is the name of person1 of type string and not the literal "Jerred"? Because the object could be mutated to contain any other string. What happens when I want to pass those objects to a function that requires name to be "Jerred"? function handleJerred(name: "Jerred") { // do something } // these are okay handleJerred(name); handleJerred(person2.name); handleJerred(person1.name);Argument of type 'string' is not assignable to parameter of type '"Jerred"'. As we鈥檇 expect, the types don鈥檛 match up. The most obvious way is to annotate the variable declaration with the expected type: const person1: { name: "Jerred" } = { name: "Jerred", }; // okay handleJerred(person1.name); We could also use the satisfies keyword. This keyword is a bit esoteric and not very common, but it comes in handy in some scenarios where you鈥檇 otherwise pull your hair out. Here鈥檚 a quick example just to show the syntax: const person1 = { name: "Jerred", } satisfies { name: "Jerred" }; // okay handleJerred(person1.name); satisfies is an alternative to an explicit variable type annotation. It tells TypeScript that your assignment should be at least assignable to the provided type. It鈥檚 kind of like a type-safe way to cast values. The benefit of satifies over an variable type annotation is that it lets TypeScript infer a mo...
First seen: 2025-11-22 22:16
Last seen: 2025-11-23 16:18