Sub topic 8
Validating shapes with `as const satisfies`
This chapter assumes you know what as const does to object and array literals, how to derive a union with (typeof X)[number], and the basics of union and literal types. It also assumes you can read an error message about readonly assignability. You need TypeScript 4.9 or later, because satisfies was added in that release.
By the end you will be able to check a constant against a type without losing its literal types. You will also know the errors that this combination produces and how to fix them.
The problem: validation and precision pull in opposite directions
A constant that describes your program, such as a route table, a theme, or a permission map, usually has two requirements:
- It must match an agreed shape, so typos and missing fields are caught.
- It must keep its exact values in the type, so you can derive unions like
"/users" | "/orders"from it.
Each tool you have met so far provides only one of these.
A type annotation validates the value, but the variable then has the annotated type, and everything more specific is discarded:
type Route = { path: string; method: "GET" | "POST" };
const annotated: readonly Route[] = [
{ path: "/users", method: "GET" },
{ path: "/users", method: "POST" },
{ path: "/orders", method: "GET" },
];
type AnnotatedPath = (typeof annotated)[number]["path"];
// string (the literal paths are gone)as const keeps every literal, but it checks nothing against your intended shape:
const routes = [
{ path: "/users", method: "GET" },
{ path: "/users", method: "PUT" }, // not a valid method, and no error
{ path: "/orders" }, // missing method, and no error
] as const;This compiles. The mistake surfaces later, when some function receives these routes, or never, if nothing consumes them with a strict type.
What `satisfies` does on its own
The satisfies operator checks that an expression is assignable to a type, but it does not change the type of the expression. The expression's own inferred type is kept. The target type is also used as a contextual type, which affects how literals are inferred:
type Route = { path: string; method: "GET" | "POST" };
const a = { path: "/users", method: "GET" } satisfies Route;
// { path: string; method: "GET" }method stays "GET" because the contextual type contains literal types, so the compiler has a reason to keep the literal. path widens to string because the contextual type is plain string, which gives no reason to keep "/users". Arrays have a similar gap. A satisfies check alone infers array elements as a mutable array type, not a tuple, so positions are not tracked.
So satisfies alone gives you validation and some precision, but only where the target type happens to contain literals. as const closes the gap.
Putting them together
Write as const first and satisfies after it:
type Route = { path: string; method: "GET" | "POST" };
const routes = [
{ path: "/users", method: "GET" },
{ path: "/users", method: "POST" },
{ path: "/orders", method: "GET" },
] as const satisfies readonly Route[];
type Path = (typeof routes)[number]["path"];
// "/users" | "/orders"
type Method = (typeof routes)[number]["method"];
// "GET" | "POST"The expression is parsed as (literal as const) satisfies T. The const assertion produces the readonly tuple with literal types, and satisfies then checks that result against readonly Route[]. The variable keeps the type from the as const step.
Now the earlier mistakes are caught where they are written:
type Route = { path: string; method: "GET" | "POST" };
const badRoutes = [
{ path: "/users", method: "GET" },
{ path: "/users", method: "PUT" },
// error: Type '"PUT"' is not assignable to type '"GET" | "POST"'
] as const satisfies readonly Route[];A missing property is reported on the element that lacks it. An extra property that the target type does not declare is reported too, because satisfies applies excess property checking to object literals:
type Route = { path: string; method: "GET" | "POST" };
const extra = [
{ path: "/users", method: "GET", handler: "list" },
// error: Object literal may only specify known properties,
// and 'handler' does not exist in type 'Route'
] as const satisfies readonly Route[];If you want extra fields to be allowed, widen the target type, for example Route & Record<string, unknown>, or add an optional field to Route.
Using the derived types
The point of keeping literals is that you can derive precise types from the data. This complete example uses the routes table to build a type guard and to pick out the paths of one method:
type Route = { path: string; method: "GET" | "POST" };
const routes = [
{ path: "/users", method: "GET" },
{ path: "/users", method: "POST" },
{ path: "/orders", method: "GET" },
] as const satisfies readonly Route[];
type RouteEntry = (typeof routes)[number];
type Path = RouteEntry["path"];
type GetPath = Extract<RouteEntry, { method: "GET" }>["path"];
// "/users" | "/orders"
function isPath(value: string): value is Path {
return routes.some((route) => route.path === value);
}
const target: string = "/orders";
if (isPath(target)) {
const p: Path = target; // narrowed from string to "/users" | "/orders"
console.log(p);
}Extract works here even though every property is readonly, because readonly does not affect whether one object type is assignable to another.
Key-based validation with `Record`
Another common target is a dictionary type. Record<string, T> checks every value but allows any key. keyof typeof then gives you the actual keys, because as const kept them:
type Theme = { color: `#${string}`; size: number };
const themes = {
light: { color: "#fff", size: 12 },
dark: { color: "#000", size: 14 },
} as const satisfies Record<string, Theme>;
type ThemeName = keyof typeof themes;
// "light" | "dark"
type DarkSize = (typeof themes)["dark"]["size"];
// 14If you annotated themes as Record<string, Theme>, ThemeName would be string and DarkSize would be number.
You can also require an exact set of keys by using a union you already have as the Record key type. The compiler then reports any missing key:
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number];
type Action = "read" | "write" | "delete";
const permissions = {
admin: ["read", "write", "delete"],
editor: ["read", "write"],
viewer: ["read"],
// Removing the viewer line gives:
// error: Property 'viewer' is missing in type ... but required in type 'Record<Role, ...>'
} as const satisfies Record<Role, readonly Action[]>;
type Granted = (typeof permissions)[Role][number];
// "read" | "write" | "delete"Adding a new role to ROLES now causes a compile error here until permissions handles it. That is the exhaustiveness check you would otherwise get from a switch on an enum.
Comparing the four options
| Form | Validates the shape | Keeps literal values | Readonly | Result type of the variable |
|---|---|---|---|---|
| `const x: T = value` | Yes | No | Only if `T` says so | `T` |
| `const x = value as const` | No | Yes | Yes | The exact readonly literal type |
| `const x = value satisfies T` | Yes | Only where `T` contains literals | No | The inferred type, narrowed by `T` as context |
| `const x = value as const satisfies T` | Yes | Yes | Yes | The exact readonly literal type |
The last row is the only one that gives you all three. If you do not need to derive types from the value, a plain annotation is simpler and gives clearer error messages.
Gotcha: the target type must accept readonly
This is the error you will meet most often. After as const, arrays are readonly tuples. A mutable target such as Route[] rejects them:
type Route = { path: string; method: "GET" | "POST" };
const routes = [
{ path: "/users", method: "GET" },
] as const satisfies Route[];
// error: The type 'readonly [{ readonly path: "/users"; readonly method: "GET"; }]'
// is 'readonly' and cannot be assigned to the mutable type 'Route[]'.The fix is to write readonly Route[]. The same rule applies to arrays nested inside the target type. If Route has a field tags: string[], a literal tags: ["a", "b"] fails after as const. Declare the field as readonly string[] instead:
type Page = { title: string; tags: readonly string[] };
const home = {
title: "Home",
tags: ["intro", "welcome"],
} as const satisfies Page;
type HomeTag = (typeof home)["tags"][number];
// "intro" | "welcome"Making the target type readonly is the correct direction. A readonly type accepts both readonly and mutable values, so you do not lose flexibility for other callers.
Gotcha: order and placement
Write as const satisfies T. The reverse, value satisfies T as const, does not do what you want: the const assertion has to apply to the literal itself, and the checker restricts what it accepts. If you find yourself reaching for the reverse order, you are probably trying to validate after the fact. Keep the literal expression and both operators together on the same declaration.
A second placement issue is that satisfies checks the expression, not the variable. If you assign the constant to another variable and mutate through a looser type, nothing re-checks the shape.
Gotcha: it is all compile-time
Both as const and satisfies are erased when the code compiles to JavaScript. The check runs when you build, against the literal you wrote. It does not protect you from data that arrives at runtime:
type Route = { path: string; method: "GET" | "POST" };
const known = [
{ path: "/users", method: "GET" },
] as const satisfies readonly Route[];
// This value comes from outside the program, so TypeScript knows nothing about it.
const incoming: unknown = JSON.parse('[{"path":"/x","method":"DELETE"}]');
// Casting would silence the compiler but not make the data valid:
const unsafe = incoming as readonly Route[];
console.log(unsafe[0].method); // "DELETE" at runtime, typed as "GET" | "POST"Use a runtime validator, such as a schema library or a hand-written type guard, for external data. as const satisfies is for constants that live in your source code. Also remember that as const does not freeze anything. Use Object.freeze if you need runtime immutability, as covered earlier in this tutorial.
Gotcha: wide target types hide mistakes
satisfies can only reject what the target type rejects. If you use Record<string, unknown> or object as the target, nearly everything passes, and you get literal types but little validation. Make the target type as specific as the contract you care about. Name the allowed literals in a union, mark required fields as required, and use a key union instead of string when the set of keys is known.
When to choose which
Use as const satisfies T when all of the following hold:
- The value is a constant written in your source code.
- Other types or functions are derived from its exact contents.
- There is a shape it must follow, and you want mistakes reported at the declaration, not at a distant call site.
Prefer a plain annotation when you only need the shape and no derived types, or when callers should see the friendly named type T in hover text and error messages. Prefer plain as const when no agreed shape exists. Prefer plain satisfies when the target type already contains the literals you care about and you do not want everything marked readonly.
Looking ahead
You can get close to this behavior inside a generic function with a const type parameter, which asks the compiler to infer arguments as if as const had been written at the call site. A const type parameter combined with an extends constraint plays the same role that satisfies plays for a variable: the constraint is the shape, and the const modifier preserves the literals. The next chapters cover this.
Exercise
The following code does not compile. Explain why, and fix it so that Level is "low" | "high" and a typo in a level value would be reported.
type Alert = { id: number; level: "low" | "high" };
const alerts = [
{ id: 1, level: "low" },
{ id: 2, level: "high" },
] as const satisfies Alert[];
type Level = (typeof alerts)[number]["level"];
Show answer
as const turns the array into a readonly tuple, and a readonly tuple cannot be assigned to the mutable type Alert[]. Change the target to readonly Alert[]:
const alerts = [
{ id: 1, level: "low" },
{ id: 2, level: "high" },
] as const satisfies readonly Alert[];
type Level = (typeof alerts)[number]["level"]; // "low" | "high"
A misspelled value such as level: "medium" is now reported at that element, because it is not assignable to "low" | "high".
Exercise
Given const MODES = ["fast", "safe"] as const; and type Mode = (typeof MODES)[number];, write a constant labels that must have exactly one string label for each mode, and keeps the literal label text in its type. What happens if you add "debug" to MODES later?
Show answer
Use Record<Mode, string> as the target:
const labels = {
fast: "Fast mode",
safe: "Safe mode",
} as const satisfies Record<Mode, string>;
Because of as const, (typeof labels)["fast"] is "Fast mode", not string. After "debug" is added to MODES, Mode includes "debug", and the satisfies check reports that property debug is missing from labels until you add it.
Exercise
Why is as const satisfies SomeType not a replacement for validating a JSON response from a server?
Show answer
Both operators are erased at compile time. The compiler checks only the literal written in your source file. A server response is produced at runtime, so its contents are unknown to the compiler, and a cast would not check them. You need a runtime check, such as a schema validator or a type guard that inspects the parsed data.