Sub topic 3
Why as assertions are not a fix
This chapter assumes you know basic TypeScript types, interfaces and type aliases, union and literal types, and Record. You should also know how inference and annotations work. The previous chapter showed that a type annotation widens a value to the declared type. A common reaction is to reach for as, which looks like a way to keep control of the type. This chapter shows why it doesn't work.
Each snippet below is standalone. If you paste several into one file, rename the repeated types and variables.
What an assertion actually does
An assertion has the form expression as Type. It tells the compiler to treat the expression as Type. It does not convert the value, and it does not emit any runtime code. The compiled JavaScript contains only the expression.
The compiler allows an assertion when the two types sufficiently overlap. In practice, either the expression's type must be comparable to the asserted type, or the asserted type must be comparable to the expression's type. Comparable is close to assignable, but looser. For example, a union is comparable to a type if any one of its members is.
This rule is why assertions are not a type check. An ordinary check asks whether the value fits the type. An assertion only asks whether the two types could plausibly describe the same value. A wide range of mistakes pass that test.
The result of an assertion always has the asserted type. TypeScript does not keep the type it inferred for the expression, so the result can be wider than the value (an upcast) or narrower than what the compiler knows is true (a downcast).
Problem 1: the asserted type replaces the inferred type
Recall the palette from the previous chapter. This version uses an assertion instead of an annotation:
type Color = "red" | "green" | "blue";
type RGB = [number, number, number];
const palette = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255],
} as Record<Color, string | RGB>;
// Error: Property 'toUpperCase' does not exist on type 'string | RGB'.
// palette.green.toUpperCase();This compiles, but palette has the type Record<Color, string | RGB>. TypeScript has forgotten that green is a string, which is the same loss as with the annotation. The assertion gave you nothing the annotation did not, so it does not solve the problem.
Problem 2: missing properties pass silently
An annotation forces an object literal to supply every required property. An assertion does not:
type Options = { port: number; host: string };
const options = {} as Options;
console.log(options.port); // undefined at runtime, typed as number
console.log(options.host.toLowerCase()); // TypeError at runtime: host is undefinedThe code compiles with no errors, but the last line throws. The assertion passes because Options is assignable to {}. The overlap test succeeds, and TypeScript accepts your claim that the empty object is an Options.
This is a pattern people use deliberately, for example to build an object up in steps. It turns off the compiler's most basic safeguard for that variable. Every later use of options is trusted even though nothing guarantees the properties exist.
The same thing happens when a type changes later. Suppose host was added to Options months after this code was written:
type Options = { port: number; host: string };
// This line was written when Options had only 'port'.
const options = { port: 80 } as Options;
console.log(options.host.toLowerCase()); // compiles, throws at runtimeThe assertion still compiles after the type changes, so the compiler does not flag any call site that needs updating. A check that fails when the type changes is what you want in a refactor. An assertion is silent in exactly that case.
Problem 3: typos and excess properties pass silently
A fresh object literal assigned to a typed variable gets excess property checking. TypeScript rejects properties that do not exist in the target type. Assertions skip this check:
type Options = { port: number; host?: string };
// An assertion compiles without complaint, so the typo goes unnoticed.
const asserted = { port: 80, hots: "localhost" } as Options;
console.log(asserted.host); // undefined: the value went into 'hots'The literal's type { port: number; hots: string } is assignable to Options. Assignability between types ignores extra properties. Only the special check for fresh object literals catches them, and that check does not run for assertions.
Misspelled optional properties are the worst case. Here host is optional, so even without the typo the type would look fine. The typo means your host setting is never read, and the compiler stays quiet.
Problem 4: wrong values sometimes pass
Assertions do catch some errors. If the value's type and the target type cannot overlap at all, the compiler refuses:
type Options = { port: number; host?: string };
// Error (TS2352): Conversion of type '{ port: string; }' to type 'Options'
// may be a mistake because neither type sufficiently overlaps with the other.
// const wrong = { port: "80" } as Options;The error message itself suggests the escape hatch, which is to convert through unknown:
type Options = { port: number; host?: string };
const forced = { port: "80" } as unknown as Options;
console.log(forced.port.toFixed(0)); // TypeError at runtime: toFixed is not a functionEverything is assignable to unknown, and unknown is comparable to everything, so a double assertion always compiles. You are then claiming something that is false, and the compiler can no longer help.
The overlap test also has gaps without the double assertion. When the types overlap only partially, the assertion is accepted even though the value may not fit. Treat the TS2352 error as a partial safety net, not as validation.
Comparing the three tools
The table summarizes what each approach does to an object literal. The satisfies column is covered in detail in the next chapter.
| Behavior | Annotation (`: T`) | Assertion (`as T`) | `satisfies T` |
|---|---|---|---|
| Reports a missing required property | Yes | Usually no | Yes |
| Reports a misspelled or excess property | Yes | No | Yes |
| Reports a value of the wrong type | Yes | Only if the types cannot overlap | Yes |
| Type of the resulting variable | The declared type `T` | The asserted type `T` | The inferred type of the expression |
| Emits runtime code | No | No | No |
An annotation has strong checking but loses precision. An assertion has weak checking and also loses precision. The satisfies column is the only one that is strong on both.
The same palette with satisfies
For contrast, here is the palette written with satisfies. The next chapter explains the syntax. For now, notice that the compiler checks the object and the types stay precise:
type Color = "red" | "green" | "blue";
type RGB = [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()); // green is known to be a stringReplacing satisfies with as here keeps the code compiling but loses the type of green. Removing the blue entry, or misspelling it, is an error with satisfies and passes with as in many forms.
When assertions are still the right tool
Assertions are not wrong in general. They exist for cases where you know something the compiler cannot. These are the usual legitimate uses:
- DOM lookups, where you know the element type from the page:
document.querySelector("#name") as HTMLInputElement | null. - Narrowing a value after your own runtime check that TypeScript cannot follow.
- Values from outside the type system, such as
JSON.parseresults, where you accept the risk. Parsing and validating the data with a schema library is safer. - Tests, where you build a partial object on purpose and only exercise part of it.
Each of these is a claim about information the compiler lacks. In all of them, you take responsibility for the claim being true. An object literal is the opposite case, because the compiler can see the full value. Using as there throws away a check the compiler could have done for you.
A related feature, as const, is also called a const assertion, but it behaves differently. It does not claim a type that you choose. It asks TypeScript to infer the narrowest type for the literal, so it cannot make false claims. It combines well with satisfies, as a later chapter shows.
Why the "as is a shortcut" intuition fails
Developers often reach for as because it silences an error quickly, and the error disappears for a reason. A type error usually means one of two things:
- The code is wrong, and the compiler found a real bug.
- The code is right, but the compiler lacks information.
An assertion is a correct fix only for the second case. For the first, it hides the bug. When you are not sure which case applies, an assertion buries the evidence. A check that can fail, such as an annotation or satisfies, keeps the evidence visible.
For object literals, the second case is rare. The compiler sees the exact shape of the literal, so it has all the information. If an annotation produces an error, either the literal is wrong or the annotation widens more than you want. The first is a bug to fix. The second is the problem satisfies addresses.
A practical review checklist
When you see as in code review, ask these questions in order:
- Is the expression an object literal or array literal being assigned to a known type? If so, replace the assertion with
satisfies, or an annotation if the wide type is enough. - Does the assertion go through
unknown? If so, the author is overriding the compiler. Look for a runtime check or a narrower design. - Is the assertion backed by a runtime check nearby, such as a type guard or a schema parse? If so, consider a user-defined type guard so the check and the type stay together.
- Is the claim about something the compiler cannot know, such as the DOM? If so, the assertion is probably fine. A comment explaining why helps the next reader.
Exercise
This code compiles. What does config.timeout evaluate to at runtime, and why does the compiler not complain?
type Config = { retries: number; timeout: number };
const config = { retries: 3 } as Config;
console.log(config.timeout);
Show answer
It prints undefined. The object literal has no timeout property, and an assertion does not add one. The compiler accepts the assertion because Config is assignable to the literal's type { retries: number }, so the types overlap sufficiently. The result is typed as Config, so config.timeout is typed as number even though it is missing. Writing { retries: 3 } satisfies Config would report the missing timeout property.
Exercise
Given type Options = { port: number; host?: string }, which of these lines produce a compile error: (a) const a = { port: 80, hots: "x" } as Options; (b) const b = { port: 80, hots: "x" } satisfies Options; (c) const c: Options = { port: 80, hots: "x" }; (d) const d = { port: "80" } as Options;
Show answer
(b), (c) and (d) produce errors. (b) and (c) fail excess property checking because hots is not in Options. (d) fails because { port: string } and Options cannot overlap, so the compiler reports TS2352. (a) compiles, because assertions skip excess property checking and the literal's type is assignable to Options.
Exercise
Why does const p = { red: [255, 0, 0], green: "#00ff00" } as Record<"red" | "green", string | [number, number, number]> lose the information that p.green is a string, even though the compiler can see the literal?
Show answer
The type of an assertion expression is the asserted type, not the inferred type of the expression. The compiler's inferred type, with green as string, is discarded and replaced by Record<..., string | [number, number, number]>. In that type every property is the union, so green is string | [number, number, number].