0
0
Typescriptprogramming~5 mins

Satisfies operator in Typescript

Choose your learning style9 modes available
Introduction

The satisfies operator helps check if a value matches a specific type without changing the value. It keeps your code safe and clear.

When you want to make sure an object fits a certain shape but keep all its details.
When you want to catch mistakes early by checking types during coding.
When you want to write clear code that shows what type a value should have.
When you want to avoid extra type conversions but still check types.
When you want to use complex types and ensure your data matches them.
Syntax
Typescript
const variable = value satisfies Type;

The satisfies operator checks the type but does not change the value's type.

This helps catch errors without losing information about the value.

Examples
This checks that user has a name as string and age as number.
Typescript
const user = {
  name: "Alice",
  age: 30
} satisfies { name: string; age: number };
This checks that colors is an array of strings that cannot be changed.
Typescript
const colors = ["red", "green", "blue"] satisfies readonly string[];
This checks that point has x and y as numbers, extra z is allowed.
Typescript
const point = { x: 10, y: 20, z: 30 } satisfies { x: number; y: number };
Sample Program

This program defines a type Person and checks that person fits it. Extra property city is allowed. Then it prints the person object.

Typescript
type Person = {
  name: string;
  age: number;
};

const person = {
  name: "Bob",
  age: 25,
  city: "New York"
} satisfies Person;

console.log(person);
OutputSuccess
Important Notes

The satisfies operator is new in TypeScript 4.9 and later.

It helps keep extra properties without errors, unlike direct type annotations.

Summary

The satisfies operator checks if a value matches a type without changing it.

It helps catch mistakes and keep extra details in your data.

Use it to write safer and clearer TypeScript code.