as any and as const
Two assertions look alike and do opposite things. as any tells the compiler to stop checking a value. as const tells it to check the value more precisely. One should be rare, the other you will reach for often.
The rule
as any switches checking off; as const locks values down.
as any turns a value into type any, which allows every operation:
const data = response as any;
data.tasks.map((t: any) => t.titel.toUpperCase()); // compilesThe typo titel sails through, and so would calling something that is not a function. Checking resumes only when the value is assigned to something with a real type. as any is an escape hatch for moments when the types are genuinely wrong or unavailable. It spreads quietly, so keep it rare and local, and prefer unknown (covered in the last section) when you just do not know the type yet.
as const is a const assertion. It makes the compiler infer the narrowest type it can:
const statuses = ["todo", "doing", "done"] as const;
// type: readonly ["todo", "doing", "done"]
statuses[0]; // "todo", not just string
statuses.push("x"); // error: readonly
const defaults = { status: "todo", done: false } as const;
// type: { readonly status: "todo"; readonly done: false }Three effects, all at once:
- Literal types —
"todo"stays"todo"instead of widening tostring. - readonly — properties and elements cannot be reassigned.
- Tuples — an array literal becomes a fixed, read-only tuple.
A handy pattern: build a union type from a constant list, so the values exist at runtime and as a type:
type Status = (typeof statuses)[number]; // "todo" or "doing" or "done"Like every assertion, both are erased: the output JavaScript is the same as without them.
The shortcut
Ask "Am I adding information or removing it?" as const adds precision the compiler can check. as any removes checking. Adding is almost always welcome; removing needs a reason you could explain in a code review.
Plain array
const statuses = ["todo", "doing", "done"];is inferred asstring[]. Any string could be pushed in.
Drills
Answer fast — trust the rule.
What is the type of const s = ["a", "b"] as const;?
After const d = response as any;, what does d.nothing.here() do at compile time?
With const cfg = { mode: "dark" } as const;, what happens on cfg.mode = "light";?
Which statement about as const and as any is true?
Remember
- as any switches checking off; as const locks values down.
- Ask "am I adding information or removing it?"
- Trap:
as anyspreads silently — keep it rare and local, and tryunknownfirst.
