TypeScript Assertion Discipline
An assertion is a claim the checker trusts without proof, and disciplined code treats that trust as a last resort. The as const form is the safe everyday case because it narrows a value instead of inventing one.
as const keeps literal types
The roles array becomes a readonly tuple of literals. Reading its element type back gives the exact union of role names.
const roles = ['admin', 'editor', 'viewer'] as const;
type RoleName = (typeof roles)[number];
const current: RoleName = 'editor';
console.log(current);
console.log(roles.length);A readonly tuple refuses push
The readonly part of as const is enforced by the checker. Adding a member to the tuple fails to compile.
const roles = ['admin', 'editor'] as const;
roles.push('viewer');
console.log(roles.length);A wrong assertion compiles and lies
The assertion claims the string is a number, and the checker believes it. Addition follows string rules at runtime, and the typeof line exposes the lie.
const n = '5' as unknown as number;
console.log(n + 1);
console.log(typeof n);A double assertion states a forced conversion
The runtime object really holds a numeric port, and only the checker cannot see it. Passing through unknown states the forced conversion openly.
const externalValue: object = { port: 8080 };
const settings = externalValue as unknown as { port: number };
console.log(settings.port);
console.log(typeof settings.port);Example
const levels = ['basic', 'pro'] as const;
type LevelName = (typeof levels)[number];
function priceFor(level: LevelName): number {
return level === 'pro' ? 20 : 0;
}
const settings = { level: 'pro', seats: 2 } as const;
console.log(priceFor(settings.level));
console.log(settings.seats);Key points
- The as const form makes a value readonly and keeps its exact literal types.
- An array with as const becomes a readonly tuple of literals instead of a mutable array of wider types.
- An assertion performs no runtime check and no runtime conversion.
- Narrow first with real checks whenever a check can prove the shape.
- Assert last, only for facts the checker cannot see but the code has already established.
- A conversion across unrelated shapes must pass through unknown instead of a direct assertion.
In this example, as const keeps the level member at the literal pro, so the settings object passes straight into a function that accepts only the literal union.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
What does as const do to an array literal?