Sub topic 8
as const satisfies: literal types that are still validated
This chapter assumes you know what satisfies does at a basic level and have seen Record, keyof, typeof and union types. You should also know that as const exists, but it is explained again here. By the end you will be able to write as const satisfies T, derive union types from the result, and avoid the readonly array error that trips up most people the first time.
Two tools with opposite strengths
Earlier chapters showed that satisfies checks an expression against a type without replacing the type TypeScript infers. That inference is not always as precise as you want. Consider this object:
const routes = {
home: "/",
user: "/users/:id",
} satisfies Record<string, string>;
// routes.home has the type string, not "/"TypeScript infers string for each property because the object is mutable. Someone could later write routes.home = "/other", so the safe inferred type is the general one. You can see the same behavior without satisfies:
const mutable = { home: "/" };
// mutable has the type { home: string }The as const assertion changes this. It tells TypeScript to infer the narrowest possible type for a literal expression:
- String, number and boolean values keep their exact literal types, such as
"/"instead ofstring. - Object properties become
readonly. - Array literals become
readonlytuples with known length and element types.
as const has a weakness, though. It validates nothing. It is an assertion about how to read the expression, not a check against a contract. A misspelled key, a missing property or a wrong value all pass unnoticed.
| Tool | Keeps literal types | Validates against a contract |
|---|---|---|
| Type annotation | No, widens to the declared type | Yes |
| `satisfies` alone | Only where the contract forces it | Yes |
| `as const` alone | Yes | No |
| `as const satisfies T` | Yes | Yes |
The last row is the subject of this chapter.
The syntax
You write the two operators in this order:
const routes = {
home: "/",
user: "/users/:id",
} as const satisfies Record<string, `/${string}`>;
type Route = (typeof routes)[keyof typeof routes]; // "/" | "/users/:id"Read it left to right. The object literal is first turned into a fully literal, readonly type by as const. Then satisfies checks that this resulting type is assignable to Record<string, /${string}>. The type of routes is the as const type, and satisfies only gives a pass or a fail.
The contract here says that every value must be a string beginning with a slash. If you add a route that does not, the compiler stops you:
const brokenRoutes = {
home: "/",
about: "about", // Error: Type '"about"' is not assignable to type '`/${string}`'.
} as const satisfies Record<string, `/${string}`>;Because as const preserved "about" as a literal, the error message names the exact value. Without as const, TypeScript would have to decide separately whether the widened string fits the template literal type, and it would not.
The order matters. Writing satisfies first and as const second does not work. A const assertion can only be applied directly to a literal expression, and { ... } satisfies T is no longer a bare literal as far as the assertion is concerned. Always put as const immediately after the literal.
Deriving types from a single source of truth
The main reason to use this pattern is that it lets one object serve as both runtime data and the source of types. You declare the values once and compute the unions from them.
const httpStatus = {
ok: 200,
created: 201,
notFound: 404,
} as const satisfies Record<string, number>;
type StatusName = keyof typeof httpStatus; // "ok" | "created" | "notFound"
type StatusCode = (typeof httpStatus)[StatusName]; // 200 | 201 | 404
function describe(code: StatusCode): string {
switch (code) {
case 200:
return "OK";
case 201:
return "Created";
case 404:
return "Not Found";
}
}
console.log(describe(httpStatus.created)); // CreatedThe switch has no default branch. Because StatusCode is exactly 200 | 201 | 404, TypeScript knows the cases are exhaustive and accepts the function without a "not all code paths return a value" error. If you add serverError: 500 to the object, StatusCode grows to include 500, and describe immediately fails to compile until you handle it. The type follows the data.
Compare the alternatives:
- With only a type annotation such as
Record<string, number>,StatusNamewould bestringandStatusCodewould benumber. The exhaustiveness benefit is gone. - With only
as const, you would get the same derived types, but nothing would stop you from writingnotFound: "404"as a string by mistake. - With
as const satisfies Record<string, number>, you get the precise types and the check that every value is a number.
Note that Record<string, number> uses string as the key type, and satisfies does not widen the keys of httpStatus to string. The variable keeps its own known keys, which is what makes keyof typeof httpStatus useful.
A lookup helper
A typical use is a function that accepts only names that exist in the object:
const routes = {
home: "/",
user: "/users/:id",
settings: "/settings",
} as const satisfies Record<string, `/${string}`>;
type RouteName = keyof typeof routes;
function link(name: RouteName): string {
return routes[name];
}
console.log(link("user")); // /users/:id
// link("profile"); // Error: Argument of type '"profile"' is not assignable to parameter of type 'RouteName'.The return type of routes[name] is "/" | "/users/:id" | "/settings", which is assignable to string. If you want callers to see the exact string, omit the : string annotation and let TypeScript infer the return type. Then link("user") still returns the union, because the function does not know which name you passed. To narrow it per call you would need a generic parameter, which is a separate technique.
Validating nested structures
Real configuration objects mix strings, numbers, arrays and nested objects. You can describe the contract as an inline type and still keep every literal:
const config = {
env: "production",
regions: ["eu-west-1", "us-east-1"],
retry: { attempts: 3, backoffMs: 250 },
} as const satisfies {
env: "development" | "production";
regions: readonly string[];
retry: { attempts: number; backoffMs: number };
};
type Region = (typeof config.regions)[number]; // "eu-west-1" | "us-east-1"
type Attempts = typeof config.retry.attempts; // 3
console.log(config.regions.length); // 2Three checks happen here. env must be one of two literals, so a typo such as "prod" fails. regions must be an array of strings. retry must contain exactly the two numeric properties, and excess property checking from the previous chapter still applies, so adding retires: 5 would be reported.
Meanwhile config.regions is typed as readonly ["eu-west-1", "us-east-1"], a tuple of two known strings, so Region is a union of the two region names rather than string.
The readonly array caveat
The most common error with this pattern involves arrays. as const turns array literals into readonly tuples. If your contract says string[], which is a mutable array type, the check fails, because a readonly array is not assignable to a mutable one. The reason is that a mutable type would allow push and other mutations that the readonly tuple forbids.
// Error: The type 'readonly ["a", "b"]' is 'readonly' and cannot be assigned to the mutable type 'string[]'.
// const bad = ["a", "b"] as const satisfies string[];
const ok = ["a", "b"] as const satisfies readonly string[];
// ok has the type readonly ["a", "b"]The fix is to write readonly in the contract. This applies at any depth. If the contract has { tags: string[] } and the value has tags: ["x"] under as const, you must change the contract to { tags: readonly string[] }.
Tuples follow the same rule:
const origin = [0, 0] as const satisfies readonly [number, number];
// origin has the type readonly [0, 0]A related consequence shows up when you pass these values to other code. A function declared as function total(values: number[]) will not accept readonly [1, 2, 3]. You can fix such functions by changing the parameter to readonly number[], which also documents that the function does not modify its input. You should avoid casting the readonly away.
What each part contributes
It helps to see what you lose when you remove either operator. The following examples all use the same contract.
type Palette = Record<"primary" | "accent", `#${string}`>;
// as const only: literals are kept, but nothing is checked.
const unchecked = {
primary: "#112233",
accnt: "red", // typo and bad value, no error
} as const;
// satisfies only: checked, but the values are just strings.
const checkedOnly = {
primary: "#112233",
accent: "#445566",
} satisfies Palette;
// checkedOnly.primary has the type "#112233"? Not guaranteed; do not rely on it.
// both: checked, and the values are exact.
const palette = {
primary: "#112233",
accent: "#445566",
} as const satisfies Palette;
// palette.primary has the type "#112233"In the middle example, TypeScript may or may not keep the literal type, depending on the contract, because satisfies only preserves literals where the contextual type calls for them. Relying on that is fragile. When you need exact literals, state your intent with as const.
Limits and failure modes
as const satisfies inherits every limit of satisfies and adds a few of its own.
- No runtime effect. Both operators are erased when TypeScript compiles to JavaScript. The object is not frozen, and mutation through a cast or from plain JavaScript still works. If you need real immutability, use
Object.freeze, and note that it is shallow. If you need to validate data that arrives from outside your program, such as JSON from a network request, you need a runtime validation library. - Only literal expressions. A const assertion works on literals of strings, numbers, booleans, arrays and objects, plus references to enum members. Writing
someVariable as constis an error. If an object includes a variable or a function call as a property value, that property keeps the type of the expression, and only the surrounding structure becomes readonly. - Readonly spreads. Everything reachable from the literal becomes readonly, including nested objects and arrays. Code that later wants to modify or sort the array in place will not compile. Use
toSortedor copy the array first. - Contract is checked after the literal is fixed. Because
as construns first, values like3are the literal3, notnumber. A contract that expects exactlynumberstill accepts it, but a contract requiring a specific other literal, such asretries: 5, rejects3. This is usually what you want. - Big unions of keys. If you derive types from a large object, every added key enlarges the union, which can slow type checking in unusually large cases. This rarely matters in practice.
When to reach for it
Use as const satisfies T when all three of these are true:
- You are writing a literal object or array in your own source code.
- You want the exact values available as types, for example to build a key union, a value union, or an exhaustive
switch. - You also want a contract that catches missing keys, typos and wrong value types.
Use plain satisfies when you want the validation and normal inference is good enough. Use as const alone for simple constants where no contract exists. Use an annotation when you want the declared type to be what the rest of the code sees, such as for a public API.
Exercise
The code below fails to compile. Identify the error and fix it without removing as const or satisfies.
const flags = {
names: ["dark", "beta"],
limit: 5,
} as const satisfies { names: string[]; limit: number };
Show answer
The error is that as const makes names a readonly ["dark", "beta"] tuple, which is not assignable to the mutable string[] in the contract. Change the contract to { names: readonly string[]; limit: number }. The limit property needs no change, because a readonly property is assignable to a mutable one. After the fix, typeof flags.names[number] is "dark" | "beta".
Exercise
Write a levels object with the keys low, medium and high and the numeric values 1, 5 and 10. It must fail to compile if any value is not a number, but typeof levels[keyof typeof levels] must be exactly 1 | 5 | 10. What is the declaration?
Show answer
const levels = { low: 1, medium: 5, high: 10 } as const satisfies Record<string, number>; The as const keeps the literal values, so the derived union is 1 | 5 | 10. The satisfies Record<string, number> clause rejects any non-number value, for example medium: "5".
Exercise
A teammate says that adding as const satisfies Config to an object loaded with JSON.parse will make the program safe against malformed input. Explain why this is wrong.
Show answer
A const assertion needs a literal expression, so it cannot even be applied to the result of JSON.parse. Beyond that, both as const and satisfies exist only at compile time and are removed from the emitted JavaScript. Data that arrives at runtime is never checked. You need runtime validation, for example a schema library or hand-written checks, to guard against malformed input.