Sub topic 2
What `as const` does
This chapter assumes you know basic TypeScript types, the difference between let and const, union and literal types such as "a" | "b", and how to use typeof and keyof in type positions. It builds on the idea of literal widening: TypeScript often replaces a precise literal type like "left" with a general type like string. Here you learn what a const assertion is, what it changes, where you can write it, and which results surprise people.
Later chapters cover objects, arrays, derived unions, satisfies, and const type parameters in more detail. This chapter gives you the working model that those chapters use.
The problem a const assertion solves
TypeScript infers types from values. When it infers the type of a mutable location, it widens literals so that later assignments are possible. A let variable and an object property are both mutable, so they widen:
type Direction = "left" | "right";
function move(dir: Direction): void {
console.log(`moving ${dir}`);
}
const options = { dir: "left" };
// options has type { dir: string }
// move(options.dir);
// error: Argument of type 'string' is not assignable to parameter of type 'Direction'.The code is correct at runtime, because options.dir holds "left". The compiler rejects it because it typed the property as string, and any string could be stored there later. A const assertion tells the compiler to infer the narrowest type for an expression and not to widen it:
type Direction = "left" | "right";
function move(dir: Direction): void {
console.log(`moving ${dir}`);
}
const options = { dir: "left" } as const;
// options has type { readonly dir: "left" }
move(options.dir); // OK: the type is "left", which is assignable to DirectionYou write a const assertion by putting as const after an expression. Nothing else in the code changed.
Syntax
A const assertion looks like a type assertion, but where the type goes you write the keyword const:
const a = "left" as const;
const b = <const>"left";The two forms mean the same thing. The angle-bracket form is not allowed in .tsx files, because <const> would be parsed as a JSX tag. Most codebases use as const, and this tutorial does too.
A const assertion is not an ordinary type assertion. With value as string you claim a type, and the compiler accepts the claim if the types are sufficiently related. With as const you don't name a type. You ask the compiler to compute the most specific type it can for the literal expression. The result can't be wrong about the value, so a const assertion can't lie the way a cast can.
The three effects
When you apply as const to a literal expression, the compiler does three things:
| Effect | What changes | Example result |
|---|---|---|
| No widening | Each string, number, or boolean literal keeps its literal type | `"dark"` instead of `string` |
| Readonly properties | Every property of an object literal becomes `readonly` | `{ readonly mode: "dark" }` |
| Readonly tuples | An array literal becomes a `readonly` tuple with a fixed length | `readonly ["id", 1]` |
The effects apply recursively to everything inside the expression. Here is the result for a nested value:
const settings = {
theme: { name: "dark", shades: ["navy", "black"] },
retries: 3,
verbose: false,
} as const;
// {
// readonly theme: {
// readonly name: "dark";
// readonly shades: readonly ["navy", "black"];
// };
// readonly retries: 3;
// readonly verbose: false;
// }Each level got the treatment: the outer object, the theme object, and the shades array. You write as const once, at the outermost expression.
Primitive literals
For a single primitive literal, the only visible effect is that the type is not widened. This matters mostly when you assign to something other than a plain const:
let wide = "left"; // string
let narrow = "left" as const; // "left"
wide = "right"; // OK
// narrow = "right"; // error: Type '"right"' is not assignable to type '"left"'.
let retries = 3 as const; // 3
let enabled = true as const; // trueThe let narrow variable can be reassigned, but only to the value "left". This is rarely useful by itself. It is a good way to see what the assertion does before you apply it to larger values.
Objects
The object effect is that each property is both literal-typed and readonly. The compiler enforces readonly on assignments:
const frozen = { mode: "dark", retries: 3 } as const;
// { readonly mode: "dark"; readonly retries: 3 }
// frozen.mode = "light";
// error: Cannot assign to 'mode' because it is a read-only property.The next chapter covers objects in detail, including what happens to methods and computed keys.
Arrays
The array effect is the biggest change in shape. A plain array literal has an array type of unknown length. With as const it becomes a tuple, which has a known length and a known type at each position, and it is readonly:
const plain = ["left", "right"];
// string[]
const fixed = ["left", "right"] as const;
// readonly ["left", "right"]
const first = fixed[0];
// "left"
// fixed.push("up");
// error: Property 'push' does not exist on type 'readonly ["left", "right"]'.The readonly marker removes every mutating method from the type, including push, pop, splice, and sort. Reading methods such as map, filter, includes, and indexOf remain.
Seeing the types yourself
You can check any of these results without running the program. The typeof operator in a type position reads the inferred type, and a small helper makes two types easy to compare:
type Equal<A, B> =
(<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2)
? true
: false;
const plain = { mode: "dark" };
const frozen = { mode: "dark" } as const;
const widened: Equal<typeof plain, { mode: string }> = true;
const narrowed: Equal<typeof frozen, { readonly mode: "dark" }> = true;If either type were different from what is claimed, the assignment to true would fail to compile. You can also hover over a variable in your editor, which shows the same information.
How `as const` differs from a type annotation
You can get a literal type with an annotation, and it helps to see why as const is usually better for compound values:
const viaAnnotation: { readonly mode: "dark"; readonly retries: 3 } = {
mode: "dark",
retries: 3,
};
const viaAssertion = { mode: "dark", retries: 3 } as const;Both give the same type, but the annotation repeats every key and every literal, so the value and the type can drift apart. With as const the value is the only source of truth, and the type follows it. This one-source idea is the basis for the derived-union pattern in a later chapter.
An annotation and a const assertion also behave differently when the annotation is broad. Annotating : { mode: string } gives you string, so the literal is lost. Annotations describe what you allow, and as const records what the value is.
A subtle point: widening literals and `const`
TypeScript distinguishes two kinds of literal type. A widening literal type is what a fresh literal gets, and it turns into string, number, or boolean when copied into a mutable location. A non-widening literal type stays as it is. A const declaration gives you the widening kind, and a const assertion gives you the non-widening kind. You can see the difference when you copy the value into a let:
const plainConst = "left";
let copy1 = plainConst;
// string, because plainConst has a widening literal type
const assertedConst = "left" as const;
let copy2 = assertedConst;
// "left", because the assertion produced a non-widening literal typeBoth plainConst and assertedConst show "left" when you hover over them. Only the second one keeps that type through the copy. This is a small effect, but it explains why as const on a primitive is not always redundant.
Where you can write it
The compiler accepts a const assertion only on certain expressions:
- String, number, bigint, and boolean literals, and template literals without a free-form string type.
- Array literals and object literals.
- References to enum members.
- Parenthesized forms of the expressions above.
It rejects anything whose type is computed at runtime:
declare function getName(): string;
const ok1 = "admin" as const;
const ok2 = ["a", "b"] as const;
const ok3 = ({ id: 1 }) as const;
// const bad1 = getName() as const;
// error: A 'const' assertions can only be applied to references to enum members,
// or string, number, boolean, array, or object literals.
const name = "root";
// const bad2 = name as const;
// error: the same message, because 'name' is an identifier, not a literalThe rule makes sense once you see the purpose. The compiler can only say what a literal's exact value is when the value is written in the source. A function call returns something that is only known at runtime.
The assertion only applies to the expression it is attached to. If an object literal contains a variable, that variable keeps its own type:
const label: string = "dark";
const config = { mode: label, retries: 3 } as const;
// { readonly mode: string; readonly retries: 3 }Here mode stays string, because label was declared as string. The assertion cannot narrow a value that the compiler already treats as a general type.
Compile-time only
A const assertion exists only for the type checker. The compiled JavaScript contains no trace of it:
const frozen = { mode: "dark", retries: 3 } as const;
console.log(frozen.mode);const frozen = { mode: "dark", retries: 3 };
console.log(frozen.mode);The object is a normal, mutable JavaScript object. readonly is enforced only where the compiler can see the type. Code that casts the type away, or JavaScript code that is not type-checked, can change the values. If you need runtime protection, Object.freeze is a separate tool. A later chapter covers the difference.
Because the mermaid fence must follow the diagram format, here is the diagram in the required form:
Common mistakes
- Expecting runtime immutability. After
as const,frozen.mode = "light"is a compile error, but the same line inside a function that received the value as a plain{ mode: string }works and changes the object. - Applying it to a variable instead of a literal. Write
as conston the literal where you create the value. Writing it on a later reference to the variable produces the error shown above. - Forgetting that
readonlyspreads to nested values. Passing a deeply readonly value to code that expects a mutable type fails. The cause and the fix are the topic of a later chapter on readonly assignability. - Using it where an annotation would document intent better. If a function return value must match a public type, annotate the return type. Use
as constfor values whose literal shape you want to preserve.
Summary of the model
Hold on to three points. First, a const assertion asks the compiler for the narrowest type of a literal expression. Second, that narrow type has three parts: literals do not widen, object properties are readonly, and arrays are readonly tuples. Third, the assertion is checked at compile time only and applies only to literal expressions.
Exercise
The code below fails to compile. Explain why, and change one line so that it compiles without adding a type annotation.
type Size = "small" | "large";
function order(size: Size): string {
return one ${size} coffee;
}
const request = { size: "small", count: 2 };
order(request.size);
Show answer
request is inferred as { size: string; count: number }, because object properties are mutable and the literal "small" widens to string. A string is not assignable to Size. Adding as const to the object literal, as in const request = { size: "small", count: 2 } as const;, gives request.size the type "small", and order(request.size) compiles. The count property also becomes the literal type 2 and becomes readonly.
Exercise
What are the types of a, b, and c, and does the last line compile?
const a = ["x", "y"] as const;
const b = a[1];
let c = { n: 1 } as const;
c.n = 2;
Show answer
a is readonly ["x", "y"], and b is "y", because the tuple has a known type at index 1. c is { readonly n: 1 }. The line c.n = 2 does not compile, because n is a read-only property, and 2 is also not assignable to the literal type 1. The let keyword only lets you reassign c itself, not its properties.