Sub topic 9
Annotation, as or satisfies: how to choose
You now know three ways to attach a type to a value: a type annotation (: T), a type assertion (as T), and the satisfies operator. This chapter compares them and gives you a procedure for picking one.
It assumes you are comfortable with these topics:
- Object literals, tuples, and union and literal types.
Recordandkeyof.- The widening problem and the
satisfiessyntax from the earlier chapters.
The three tools side by side
Each tool answers a different question:
- An annotation says "this variable has type T". The compiler checks the value and then uses T from that point on.
- An assertion says "treat this value as T". The compiler only checks that the two types are related closely enough, then uses T.
satisfiessays "this value must be compatible with T". The compiler checks it and keeps the type it inferred for the value.
| Row | Annotation `: T` | Assertion `as T` | `satisfies T` |
|---|---|---|---|
| Checks the value against T | Yes | Only that the types overlap | Yes |
| Type of the expression afterwards | T | T | The inferred type |
| Excess property check on object literals | Yes | No | Yes |
| Missing required property | Error | Allowed when T is assignable to the value's type | Error |
| Can override what the compiler knows | No | Yes | No |
| Runtime effect | None | None | None |
The last row matters. All three disappear when TypeScript compiles to JavaScript, so none of them validates data at runtime.
The same object, written three ways, shows the difference:
type Color = "red" | "green" | "blue";
type RGB = [number, number, number];
type Palette = Record<Color, string | RGB>;
const annotated: Palette = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255],
};
const asserted = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255],
} as Palette;
const satisfied = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255],
} satisfies Palette;
// annotated.green.toUpperCase(); // Error: string | RGB has no toUpperCase
// asserted.green.toUpperCase(); // Error: same reason
console.log(satisfied.green.toUpperCase()); // OK: green is a string
console.log(satisfied.red.map((n) => n / 255)); // OK: red is a tupleIn annotated and asserted, every property has the type string | RGB. Only satisfied remembers that green is a string and red is a tuple. If the rest of your code reads the object by key, that precision is what you want.
When an annotation is the right choice
An annotation fixes the type of a variable, and sometimes you want exactly that. Use one in these cases.
The variable will be reassigned. An annotation states which values the variable may hold over its whole life:
type Status = "idle" | "loading" | "done";
let status: Status = "idle";
status = "loading"; // allowed: the declared type is the full union
// status = "finished"; // Error: not part of StatusWith satisfies, the variable's type comes from inference, not from the type you wrote. That inferred type may be narrower than the set of values you plan to assign later.
You are describing a boundary. Function parameters, return types, exported constants, class fields and interface members form your public contract. Writing the type there keeps the contract stable even when the implementation changes:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
export function area(shape: Shape): number {
return shape.kind === "circle" ? Math.PI * shape.radius ** 2 : shape.side ** 2;
}You want the wider type on purpose. Sometimes forgetting detail is the goal. If other code should depend only on Palette and not on the exact shape of one object, annotate it. Callers then cannot rely on details you may want to change.
The value is not a literal. Annotating the result of a function call or a new expression is usually the clearest choice. satisfies adds little there, because the type already comes from the call.
When `as` is the right choice
An assertion is the only tool of the three that can tell the compiler something it cannot work out itself. That is its job, and it is also the risk.
type User = { id: number; name: string };
const raw = '{"id": 1, "name": "Ada"}';
const user = JSON.parse(raw) as User; // JSON.parse returns any
console.log(user.name);Legitimate uses of as include:
- Narrowing the result of an API that returns a broad type, such as
anyfromJSON.parseorElementfrom a DOM query. - Marking a value as
constwithas const. - Asserting a type after you have verified it by some means the compiler cannot follow.
For the last case, the safe pattern is a runtime check next to the assertion. A type guard is the cleaner version of that pattern:
type User = { id: number; name: string };
function isUser(value: unknown): value is User {
if (typeof value !== "object" || value === null) return false;
const candidate = value as Record<string, unknown>;
return typeof candidate.id === "number" && typeof candidate.name === "string";
}
const parsed: unknown = JSON.parse('{"id": 1, "name": "Ada"}');
if (isUser(parsed)) {
console.log(parsed.name.toUpperCase());
}Do not use as to give an object literal its type. Assertions are lenient about incomplete values and extra properties:
type Options = { port: number; host?: string };
const empty = {} as Options; // compiles, but port is missing at runtime
const typo = { port: 80, hots: "localhost" } as Options; // compiles, typo unnoticed
// const wrong = { port: "80" } as Options; // Error: string and number do not overlapAn assertion is rejected only when the two types do not overlap at all. A value that is merely incomplete passes. A literal that satisfies would reject, as accepts, and you lose the protection you were trying to add.
There is also the double assertion, value as unknown as T. It silences every check. If you find yourself writing it, the types are probably telling you something. Fix the types, or validate the value, before reaching for it.
When `satisfies` is the right choice
Use satisfies when two things are true:
- You want the compiler to check a value against a type.
- You also want to keep what the compiler inferred about that value.
This happens most often with object literals that act as configuration, lookup tables or registries.
Configuration and lookup tables
The value is read by key later, and different keys have different types. satisfies with Record and a union of keys also requires every key to be present:
type Env = "dev" | "staging" | "prod";
type Settings = { url: string; retries?: number };
const settings = {
dev: { url: "http://localhost:3000" },
staging: { url: "https://staging.example.com", retries: 2 },
prod: { url: "https://example.com", retries: 5 },
} satisfies Record<Env, Settings>;
console.log(settings.dev.url);
console.log(settings.prod.retries.toFixed(1)); // retries is known to be a number hereIf you forget prod, or spell it porod, the compiler reports the object. With an annotation of Record<Env, Settings>, settings.prod.retries would still be number | undefined, and the call to toFixed would be an error.
Callbacks in a map
satisfies supplies a contextual type, so callback parameters do not need annotations. The return types you write stay precise:
type Handlers = Record<string, (input: string) => unknown>;
const handlers = {
trim: (s) => s.trim(),
size: (s) => s.length,
} satisfies Handlers;
const n: number = handlers.size("abc"); // returns number, not unknown
console.log(n, handlers.trim(" hi "));Here s is inferred as string from Handlers. If you annotated handlers as Handlers, handlers.size("abc") would return unknown, and the assignment to n would fail.
Keys that stay known
An annotation with a string index signature accepts any key on read. satisfies keeps the exact key set:
type Table = Record<string, number>;
const annotated: Table = { a: 1, b: 2 };
const satisfied = { a: 1, b: 2 } satisfies Table;
console.log(annotated.typo); // compiles; the value is undefined at runtime
// console.log(satisfied.typo); // Error: property 'typo' does not exist
console.log(satisfied.a);With the noUncheckedIndexedAccess compiler option on, the annotated version would at least report number | undefined. Even so, satisfied catches the misspelled key at compile time, which is a stronger guarantee.
A decision procedure
Work through these questions in order. The first match decides the tool.
You can also reduce the diagram to three rules of thumb:
- The compiler is missing information, so use
as, and verify the claim yourself. - The compiler has the information, but you want to constrain the value, so use
satisfies. - You want the type to be part of the contract, so use an annotation.
Combining the tools
The tools are not exclusive. Some combinations are common and useful.
as const satisfies T keeps literal values and validates them against a pattern. The type given to satisfies must be readonly when the value contains arrays, because as const makes them readonly:
const routes = {
home: "/",
user: "/users/:id",
} as const satisfies Record<string, `/${string}`>;
type Route = (typeof routes)[keyof typeof routes]; // "/" | "/users/:id"
const steps = ["build", "test"] as const satisfies readonly string[];
console.log(routes.home, steps.length);A validated value, then a deliberate widening. If you want both a checked literal and a wide public type, validate first and annotate on export:
type Color = "red" | "green" | "blue";
type RGB = [number, number, number];
const base = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255],
} satisfies Record<Color, string | RGB>;
export const palette: Record<Color, string | RGB> = base;
console.log(palette.red, base.green.toUpperCase());Inside the module you keep the precise type through base. Outside, consumers see only the public Record<Color, string | RGB>.
satisfies inside a function. It also works on a return expression, so you can check the shape of a returned object without writing out its full return type:
type Point = { x: number; y: number };
function origin() {
return { x: 0, y: 0, label: "origin" } satisfies Point; // OK: excess property check does not reject label here
}
console.log(origin().label);This works because label is not in Point, but the check on the literal happens against the expression's inferred type. If it failed, you would use a wider target type. Test such cases in your own project before relying on them, since excess property checks depend on how the target type is written.
Common mistakes when choosing
Using as to satisfy the compiler. A cast that silences an error often hides a real bug. Ask first whether the value really has that type. If you can express the requirement as a type, satisfies will check it for you.
Using an annotation and then fighting the type. If you annotate a lookup table and then add as casts at each use, you have paid for both and gained nothing. Switch the declaration to satisfies.
Expecting satisfies to protect data from outside the program. The operator checks the expression you wrote in source code. It does not examine values that arrive from files, networks or user input. It is also pointless on a value typed any, because any satisfies every type. For external data, use a runtime validator or a type guard.
Expecting satisfies to fix the variable's type. After const x = value satisfies T, x has the inferred type of value, not T. If later code needs x to accept every T, annotate it.
Forgetting the version and tooling. satisfies needs TypeScript 4.9 or later. Your editor, linter parser and any Babel or esbuild setup must also be recent enough to parse it. A parse error on the keyword usually means one of these tools is out of date.
Quick reference
| Situation | Choose |
|---|---|
| Reassigned variable | Annotation |
| Function parameter, return type or exported API | Annotation |
| Config object or lookup table read by key | `satisfies` |
| Required keys from a union, with value types kept | `satisfies` with `Record` |
| Callbacks in an object that need parameter types | `satisfies` |
| Literal values that must match a pattern | `as const satisfies` |
| Value from `JSON.parse` or a DOM query | `as`, or a type guard |
| Anything coming from outside the program | Runtime validation |
Exercise
You write const limits = { small: 10, large: 100 } satisfies Record<string, number>;. A teammate later adds the line console.log(limits.medium);. Does the compiler accept it? What changes if the declaration is const limits: Record<string, number> = { small: 10, large: 100 }; instead? Explain which version you would pick and why.
Show answer
With satisfies, limits keeps its inferred type { small: number; large: number }, so reading limits.medium is a compile error because the property does not exist. With the annotation, the type is Record<string, number>, so any key is accepted and limits.medium compiles, yielding undefined at runtime. Pick satisfies when the set of keys is fixed and code reads them by name, because it catches misspelled or missing keys. Pick the annotation only if the table is meant to accept arbitrary keys.
Exercise
Which tool fits each case: (1) let mode that starts as "light" and later becomes "dark", where the type is the union "light" | "dark"; (2) a object mapping each of the five HTTP methods in a union to a handler function whose parameters should be inferred; (3) the result of JSON.parse that you have already checked with a type guard?
Show answer
(1) An annotation, let mode: "light" | "dark" = "light", because the variable is reassigned and the declared union should govern all assignments. (2) satisfies Record<Method, Handler>, which requires every method to be present, infers the handler parameters from the contextual type, and keeps each handler's own return type. (3) The type guard itself, which narrows the value to the target type without an assertion. A plain as is acceptable only when the check happens elsewhere and the compiler cannot follow it.