Sub topic 9
Annotation, `as` or `satisfies`: How to Choose
This chapter assumes that you know TypeScript type aliases, interfaces, union and literal types, object literals, arrays, tuples, Record, and keyof. You should also know the difference between a type annotation and inferred type.
TypeScript gives you three related ways to describe an expression:
- A type annotation declares the type a variable should have.
- A type assertion using
astells TypeScript to treat an expression as a particular type. - The
satisfiesoperator checks that an expression matches a type without replacing the expression's inferred type.
The choice matters because each tool gives you a different balance between checking and precision.
The three choices
Consider this configuration type:
type Theme = {
primary: string;
spacing: number;
};You can use an annotation:
const annotatedTheme: Theme = {
primary: "#3366ff",
spacing: 8,
};The variable has type Theme. The annotation checks the object and gives the variable that declared type.
You can use an assertion:
const assertedTheme = {
primary: "#3366ff",
spacing: 8,
} as Theme;The assertion tells TypeScript to treat the expression as a Theme. It does not add a runtime check.
You can use satisfies:
const checkedTheme = {
primary: "#3366ff",
spacing: 8,
} satisfies Theme;The expression must be compatible with Theme, but TypeScript keeps the type it inferred for the object.
| Tool | Checks compatibility | Keeps precise inferred properties | Validates at runtime |
|---|---|---|---|
| Type annotation | Yes | Usually no | No |
| `as` assertion | Limited compile-time check | Depends on the assertion | No |
| `satisfies` | Yes | Yes | No |
Use an annotation when the declared type is the interface
An annotation is the clearest choice when you want the variable to be used as a broad type.
For example, a function can return one of several payment methods:
type Payment =
| { kind: "card"; lastFour: string }
| { kind: "cash" };
const payment: Payment = {
kind: "card",
lastFour: "1234",
};The variable is intentionally treated as Payment. Code that reads payment must narrow the union before using properties specific to one variant:
if (payment.kind === "card") {
console.log(payment.lastFour);
}Annotations are also useful for function parameters, public variables, class properties, and values whose implementation details should not be exposed.
An annotation can widen literal values. For example:
type Color = "red" | "green" | "blue";
const color: Color = "green";Here, color has the union type Color, not the narrower literal type "green". That is often useful because the variable may later hold another allowed color.
Use `as` only when you know more than TypeScript
An assertion is appropriate when the type system cannot observe a fact that your program guarantees.
A common example is a DOM lookup:
const input = document.querySelector("#email") as HTMLInputElement;
input.value = "[email protected]";The selector returns Element | null, but you may know from the page structure that an element with this ID is always an input. The assertion records that knowledge.
However, the assertion does not verify the claim. If the element is missing or is a different element, the program can fail at runtime.
Assertions can also hide configuration mistakes:
type Options = {
port: number;
host?: string;
};
const options = {
port: 80,
hots: "localhost",
} as Options;The misspelled hots property is not useful as host, but the assertion can allow the typo to pass. Use an assertion to express a fact that cannot be represented or checked at that point, not as a substitute for validation.
Use `satisfies` when you need checking and precision
satisfies is usually the best choice for configuration objects, lookup tables, and registries.
type Color = "red" | "green" | "blue";
type RGB = readonly [number, number, number];
const palette = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255],
} satisfies Record<Color, string | RGB>;
console.log(palette.green.toUpperCase());
console.log(palette.red.map((component) => component * 2));The Record<Color, string | RGB> type checks every key and value. At the same time, palette.green remains known as a string, and palette.red remains known as an RGB tuple. An annotation would widen both properties to string | RGB, making property-specific operations require extra narrowing.
satisfies also catches extra properties in an object literal:
type ServerOptions = {
port: number;
host?: string;
};
const server = {
port: 8080,
hots: "localhost",
} satisfies ServerOptions;TypeScript reports that hots is not a known property. This makes satisfies especially useful for data where property names are part of an exact contract.
Require complete keys with `Record`
A union of keys combined with Record requires every key:
type Environment = "development" | "test" | "production";
const apiUrls = {
development: "http://localhost:3000",
test: "http://localhost:3001",
production: "https://api.example.com",
} satisfies Record<Environment, string>;If you omit test, or write prodcution, the object fails to type-check. This is stronger than Record<string, string>, which permits any string key.
Use a less specific key type when partial data is intentional:
const optionalApiUrls = {
development: "http://localhost:3000",
} satisfies Partial<Record<Environment, string>>;Partial changes the contract so that missing keys are allowed.
Combine `as const` with `satisfies`
Use as const when you need literal values and readonly properties. Put it before satisfies:
const routes = {
home: "/",
user: "/users/:id",
} as const satisfies Record<string, `/${string}`>;
type Route = (typeof routes)[keyof typeof routes];
// "/" | "/users/:id"The template literal type ` /${string} requires every route to start with /. as const` preserves the exact route strings.
The readonly result affects the type you validate against:
const labels = ["home", "profile"] as const satisfies readonly string[];An as const array is readonly, so it cannot satisfy mutable string[]. Use readonly string[] when that immutability is intended.
A practical decision process
Use this rule of thumb:
- Choose an annotation when the declared type is the intended working type.
- Choose
satisfieswhen the expression must meet a contract but its specific inferred shape remains useful. - Choose
asonly when you have reliable information that TypeScript cannot verify.
Exercise
You are defining a complete table for the keys "small" and "large". Each value must be a number, but later code should preserve the exact properties. Which tool should you use, and what type should validate the table?
Show answer
Use satisfies: const sizes = { small: 12, large: 24 } satisfies Record<"small" | "large", number>;. It checks both required keys and value types while preserving the inferred property types.