Satisfies Keyword in TypeScript

The satisfies keyword provides a declarative way to check if a value conforms to a specific type without altering the code's runtime behavior.

Let's look at how and why to use the satisfies keyword in TypeScript:

Why Use satisfies?

satisfies asserts that a value meets a particular type without changing the resulting JavaScript after compilation. Here are a few reasons why it's beneficial:

  • Explicit Type Checking: It ensures that a value explicitly matches a type, enhancing code readability and maintainability.
  • Error Detection: By checking types at compile time, satisfies helps catch errors early in the development cycle, reducing bugs in production.
  • Doesn't Assert: Unlike type assertions that can override type checks, satisfies performs a non-invasive check that doesn’t alter the behavior or the perceived type of the variable.

How to Use Satisfies

Using satisfies is straightforward. Here’s how you can implement it in your TypeScript code:

interface User {
  id: number;
  name: string;
}

const user = {
  id: 1,
  name: "Niall",
  email: "niall@example.com"
} satisfies User;
// Using 'satisfies' to check if 'user' conforms to the 'User' interface

If the user object contains properties not in the User interface or is missing properties required by the User interface, TypeScript will throw a compile-time error.

When to use?

I find satisfies useful in any scenario where I want to confirm that a type is what I expect because asserting types can often lead to unexpected bugs slipping through.

TypeScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.