4 min read
•Question 34 of 48mediumWhat is the satisfies operator?
Type checking without widening.
What You'll Learn
- What satisfies does
- satisfies vs type annotation
- When to use it
The satisfies Operator
satisfies validates a value matches a type while preserving the specific inferred type.
code.tsTypeScript
type Colors = Record<string, string | number[]>;
// With type annotation - loses specificity
const colors1: Colors = {
red: "#ff0000",
green: [0, 255, 0]
};
colors1.red.toUpperCase(); // Error: might be array
// With satisfies - keeps specific types
const colors2 = {
red: "#ff0000",
green: [0, 255, 0]
} satisfies Colors;
colors2.red.toUpperCase(); // OK: knows it's string
colors2.green.map(n => n); // OK: knows it's arrayComparison
code.tsTypeScript
type Route = { path: string; element: string };
// Type annotation
const route1: Route = { path: "/", element: "Home" };
route1.path; // type: string
// satisfies
const route2 = { path: "/", element: "Home" } satisfies Route;
route2.path; // type: "/" (literal)Use Cases
code.tsTypeScript
// Validate object keys exist
type ValidKeys = "name" | "age";
const config = {
name: "John",
age: 30
} satisfies Record<ValidKeys, unknown>;