Skip to content
← All posts

Nov 25, 2026

Your TypeScript type is lying to you — `as` is a promise, not a check

`as` is erased when TypeScript compiles. It changes what the compiler believes, not what the value is. If the data comes from outside your code, check it at runtime — don't cast it.

TypeScriptJavaScriptdashboards

The orders table crashed on a line that TypeScript had approved. order.total.toFixed(2) — total is a number, the type says so, the compiler said so. Except the API had started sending the total as the string "149.99", and toFixed does not exist on a string. The type was a lie, and the lie came from one line:

const orders = (await res.json()) as Order[];

res.json() returns any. The cast told the compiler the shape, the compiler believed it, and from that point on nothing in the codebase questioned it. The dashboard rendered garbage with full type safety.

as does nothing at runtime

A type assertion is a note to the compiler. It is not a conversion, not a check, and not a transformation. When tsc compiles your code, the assertion is erased — the JavaScript that ships is just await res.json(). Nothing in the emitted code verifies that the value has an id, a total, or anything else. The TypeScript docs call it a type assertion rather than a cast for exactly this reason: you are asserting, and the compiler takes your word for it.

That is fine when you genuinely know more than the compiler. It is dangerous when the data comes from somewhere your code does not control — an API response, a webhook payload, localStorage, a query string. In those places the compiler has no information at all, so your assertion is not knowledge. It is a guess wearing a type.

The same applies to the non-null assertion, value!. It removes null and undefined from the type and nothing else. If the value really is null, the runtime error just arrives one line later, in a place that now has no type error pointing at it.

The escape hatch that removes the last guard

TypeScript does try to stop the worst assertions. You cannot assert a string to a number directly — the compiler refuses with error TS2352, because the two types do not overlap. But it also tells you the way around it: go through unknown first.

const price = "149.99" as unknown as number;
price + 10; // "149.9910" — still a string, at runtime

That compiles cleanly. typeof price is still "string", and price + 10 concatenates instead of adding. The compiler is happy and the value is wrong, and nothing anywhere will warn you. as unknown as T forces any assertion through, which is why it belongs in test mocks and in the rare case where a library's types are genuinely wrong — not in code that touches real data.

When a cast is the right tool

Casts are not always wrong. After a real runtime check, a cast is often the cleanest way to say what you just proved:

if (typeof value === "string") {
  value.toUpperCase(); // no cast needed — TypeScript narrowed it
}

Narrowing with typeof, in, or instanceof is better than asserting, because the check actually runs. And as const is a different, safe thing entirely — it narrows a literal and makes it read-only, it never claims a value is something it is not. satisfies is useful the same way: it checks a value against a type at compile time without changing the type. None of these check anything at runtime either — but they are honest about what they do.

The fix: check the data where it enters

If the data comes from outside your program, the only honest fix is to check it at runtime, once, at the boundary — and then let the types do their job inside. Zod is the library most TypeScript codebases reach for, and Zod 4 is the current version. You write the schema once and infer the type from it, so the check and the type cannot drift apart:

import * as z from "zod";

const OrderSchema = z.object({
  id: z.string(),
  total: z.number(),
});
type Order = z.infer<typeof OrderSchema>;

const result = OrderSchema.safeParse(await res.json());
if (!result.success) {
  // log it, show an error state — don't render garbage
  throw new Error("bad order payload");
}
const order = result.data; // really an Order now

parse throws a ZodError when the data is wrong; safeParse returns a discriminated union — { success: true, data } or { success: false, error } — which is the better choice where bad input is an expected outcome, like a request body that should become a 400 instead of a 500. The same pattern works for process.env at startup, where a missing variable should fail the deploy, not the third request of the day.

The cost is a dependency and a few milliseconds at the boundary. The saving is that every function past the boundary can trust its inputs, because something actually checked them. Inside the boundary, do not re-validate — a function that receives an Order should trust it, or validation ends up scattered everywhere with no clear owner.

What this does not fix

A schema is only as good as what you wrote in it. If you declare total: z.number() and the API genuinely sends a string, Zod rejects the whole payload — which is the correct outcome, but you still have to decide what the dashboard shows instead. And validation does not make a wrong schema right: if the field was renamed upstream and you never updated the schema, the failure moves from a silent wrong render to a loud rejected parse, which is an improvement, not a solution. For very large payloads, validate once at the boundary and pass the typed result down — never re-parse on every render.

The rule I use now: as is for values my code already proved, never for values the network handed me. If I did not create the data, I do not get to assert its shape. I check it, or I admit I am guessing.