Sub topic 12
Validating constants with satisfies
This chapter assumes you know the earlier material in this tutorial: literal types, unions of literals, as const, and the typeof/keyof pattern for deriving a union from a constant object. You should also be comfortable with Record<K, V> and with the difference between a type annotation and a type assertion.
The problem: annotations throw information away
You often have a constant object that must follow a rule. Every member of a union needs an entry, or every value must be a string or a number array. There are two obvious ways to state the rule, and each has a cost.
The first is a type annotation:
type Color = "red" | "green";
const palette: Record<Color, string | number[]> = {
red: [255, 0, 0],
green: "#00ff00",
};
// Error: Property 'map' does not exist on type 'string | number[]'.
const doubled = palette.red.map((n) => n * 2);The annotation checks the object, but afterwards the compiler only knows what the annotation says. It has forgotten that red holds an array. Every use site must narrow string | number[] again.
The second is to skip the annotation and let inference work:
const palette = {
red: [255, 0, 0],
gren: "#00ff00", // typo, nothing complains
};Inference keeps the precise types, but nothing checks the object against the rule. A typo or a missing key goes unnoticed until it causes a bug elsewhere.
You want both: the check from the annotation and the precision from inference. The satisfies operator, added in TypeScript 4.9, does this.
What satisfies does
expression satisfies Type checks that the expression is assignable to Type. It reports an error if it is not. The type of the expression is still the one inferred from the expression itself, not Type.
const palette = {
red: [255, 0, 0],
green: "#00ff00",
} satisfies Record<"red" | "green", string | number[]>;
const doubled = palette.red.map((n) => n * 2); // OK: red is still number[]
const upper = palette.green.toUpperCase(); // OK: green is still stringNow the same typo is caught:
const broken = {
red: [255, 0, 0],
gren: "#00ff00",
} satisfies Record<"red" | "green", string | number[]>;
// Error: Object literal may only specify known properties,
// and 'gren' does not exist in type 'Record<"red" | "green", string | number[]>'.The check does two jobs for object literals.
- Missing keys. If
greenwere absent, the compiler would report that propertygreenis missing. - Excess keys. Unknown property names are rejected by the same excess property check that applies to annotated literals.
Comparing the three tools
| Technique | Checks the value | Keeps the precise inferred type | Catches missing or extra keys |
|---|---|---|---|
| Type annotation (`const x: T = v`) | Yes | No, the type becomes `T` | Yes |
| Type assertion (`v as T`) | Loosely | No, the type becomes `T` | No |
| `satisfies` (`v satisfies T`) | Yes | Yes | Yes |
An assertion is the weakest option here. {} as Record<Color, string> compiles, because an empty object type overlaps with the target, and you get an object with no keys typed as if it had all of them. Use satisfies when you want validation, and keep assertions for cases where you know more than the compiler.
Contextual typing and literal preservation
The operator does more than compare types afterwards. The type after satisfies also acts as a contextual type while the compiler infers the expression. This has two visible effects.
Callback parameters get types. In an object of functions, the parameters are inferred from the target type:
type Handlers = Record<"click" | "key", (value: string) => void>;
const handlers = {
click: (v) => console.log(v.toUpperCase()), // v is string
key: (v) => console.log(v.length), // v is string
} satisfies Handlers;Without the contextual type, v would be an implicit any and fail under noImplicitAny.
Literals can survive. When the target type contains literal types, a matching value is kept as a literal instead of widening:
type Config = { mode: "dark" | "light" };
const annotated: Config = { mode: "dark" };
const checked = { mode: "dark" } satisfies Config;
// annotated.mode is "dark" | "light"
// checked.mode is "dark"For a target type that has no literal types, such as Record<Route, string>, the property still widens to string, just as it does without satisfies. Recall from the widening chapter that a mutable object property widens by default. If you want the literal values kept regardless, combine the operator with as const:
type Route = "home" | "about";
const routes = {
home: "/",
about: "/about",
} as const satisfies Record<Route, string>;
// routes.home has type "/" and is readonlyRead the order from left to right. as const runs first and freezes the literal types. satisfies then validates that frozen object.
Keeping a lookup table complete
The most common use of satisfies in code that models fixed sets is a table with one entry per member. Take the constant object and derived union from the earlier chapter on choosing between enums and unions:
const Status = {
Active: "active",
Inactive: "inactive",
} as const;
type Status = (typeof Status)[keyof typeof Status]; // "active" | "inactive"
const labels = {
active: "Currently running",
inactive: "Switched off",
} satisfies Record<Status, string>;
function label(status: Status): string {
return labels[status];
}If someone later adds Archived: "archived" to Status, the labels declaration fails to compile because the key archived is missing. The compiler points at every table that needs a new row. This is the same safety the exhaustive switch with never gives you, but for data instead of control flow.
The same pattern works with a real enum. Computed enum members work as keys:
enum Level {
Low,
Medium,
High,
}
const threshold = {
[Level.Low]: 10,
[Level.Medium]: 50,
[Level.High]: 90,
} satisfies Record<Level, number>;
console.log(threshold[Level.Medium]); // 50Removing one of the three entries is a compile error.
Gotchas and edge cases
as const arrays are readonly
as const turns arrays into readonly tuples. A mutable array type on the right of satisfies then rejects them:
// Error: The type 'readonly [255, 0, 0]' is 'readonly' and cannot be
// assigned to the mutable type 'number[]'.
const bad = { red: [255, 0, 0] } as const satisfies Record<"red", number[]>;
// OK: readonly arrays accept readonly tuples
const good = { red: [255, 0, 0] } as const satisfies Record<"red", readonly number[]>;Readonly properties on objects are not a problem, because readonly on a property does not affect assignability. Readonly arrays are.
The variable is not typed as the target
Because the inferred type is kept, a variable declared with satisfies may be narrower than you expect. This is usually the point. But if you later want to reassign it with a different valid value, use an annotation instead:
let mode = "dark" satisfies "dark" | "light";
mode = "light"; // Error: Type '"light"' is not assignable to type '"dark"'? No.That snippet is misleading, so be precise about it. For let, the inferred type of "dark" widens to string, and the satisfies check does not stop widening of mutable declarations. If you need a variable that accepts only the union, write let mode: "dark" | "light" = "dark". Use satisfies mostly with const declarations and with expressions you pass or return.
Errors can be less clear on deep objects
When a nested value does not match, the message points to the innermost mismatch, which can be several lines long. Name the target type with a type alias, as the examples above do, to keep the messages readable.
Tooling must support it
satisfies needs TypeScript 4.9 or later. Older versions of Prettier, ESLint parsers, and Babel presets fail with a syntax error, even though your own compiler is up to date. If you see a parse error on the keyword, check the versions of those tools first.
It checks the expression, not later uses
satisfies validates the value at the point of declaration only. It does not constrain what other code does with the variable. If the object is mutable, later code can still write the wrong kind of value to a property, as long as the inferred property type allows it.
When to use it
Use satisfies when all of these hold:
- the value is a constant, such as a config, a lookup table, or a map of handlers
- it must follow a type, such as a
Recordover a union, so the compiler can catch mistakes - you want to read the precise property types back without narrowing
Use a plain annotation when you want the variable to have the wider type, for example when it will be reassigned or when you intentionally hide the details. Use inference alone when no rule applies.
Summary
satisfies separates two jobs that annotations combine: checking a value against a type, and deciding the type of the variable. It validates, supplies contextual types to callbacks and literals, and leaves the inferred type intact. Paired with as const and a derived union, it makes lookup tables that fail to compile whenever the set of values changes.
Exercise
Given type Size = "s" | "m" | "l";, write a constant widths that maps each size to a number (s: 10, m: 20, l: 30) so that forgetting a size is a compile error, while widths.m keeps the type number without any narrowing. Then say what happens if you write const widths: Record<Size, number> = {...} and then access widths.m.
Show answer
const widths = { s: 10, m: 20, l: 30 } satisfies Record<Size, number>; Removing the l entry produces an error that property 'l' is missing. With the annotation form, widths.m is also number, because every value type in the record is number, so the two forms behave the same for this particular type. The difference appears when the value types vary, such as string | number[], where the annotation forgets which key holds which type and satisfies remembers.
Exercise
Why does const data = { items: [1, 2, 3] } as const satisfies { items: number[] }; fail, and how do you fix it?
Show answer
as const makes items a readonly [1, 2, 3] tuple, and a readonly array is not assignable to the mutable number[]. Change the target type to { items: readonly number[] }.