Introduction to TypeScript’s "satisfies" Operator

What is the satisfies Operator?

The satisfies operator in TypeScript allows you to check at compile time whether an object meets the structural requirements of a specific type or interface. It is used to confirm that an object complies with the conditions of an interface or type.

Basic Usage

interface Person {
    name: string;
    age: number;
}

const examplePerson = {
    name: "Alice",
    age: 30,
    location: "Seoul"
};

// Check if `examplePerson` satisfies the `Person` interface
examplePerson satisfies Person;

In the example above, the examplePerson object has the name and age properties required by the Person interface. Using the satisfies operator, you can check if this object meets the conditions of the Person interface at compile time.

Differences from the as Keyword

The as keyword in TypeScript is used for type assertions, where you tell the TypeScript compiler to treat a variable as a certain type forcefully. It is generally used when you are sure about the type of a variable, and no actual type checking is performed.

let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;

In the code above, someValue is of type any, but it is treated as a string using as string to calculate its length. This provides type information to the compiler, but no runtime type check occurs.

On the other hand, the satisfies operator verifies that an object actually meets the specific type requirements and does not perform any type conversion. This ensures code stability and helps reduce type-related bugs.

Conclusion

TypeScript’s satisfies operator enhances the precision of the type system and enables safer code development. Unlike the as keyword, which focuses on providing type information to the compiler, the satisfies operator focuses on verifying actual type compatibility, promoting stronger and safer type checks in your TypeScript codebase.