Sub topic 3
What `as const` Cannot Do
Assume you know basic TypeScript types, unions, arrays, object types, typeof, and keyof. This chapter focuses on the boundaries of as const and related patterns.
What `as const` Cannot Do
A const assertion narrows a literal expression and adds readonly in the type system. It does not freeze the value at runtime.
const settings = { retries: 3 } as const;
// settings.retries = 4; // TypeScript error
(settings as { retries: number }).retries = 4;
console.log(settings.retries); // 4The type assertion changes what the compiler permits. It does not change the JavaScript object. Use Object.freeze when runtime immutability matters.
as const also applies only to literal expressions and enum members. You cannot use it to narrow an arbitrary function result:
declare function readMode(): string;
// const mode = readMode() as const; // ErrorA value returned as string needs runtime validation before it can safely become a narrower type.
Validating Shapes with `as const satisfies`
as const preserves exact values. satisfies checks that the value matches a required shape without replacing those exact types.
type Route = {
path: string;
method: "GET" | "POST";
};
const routes = [
{ path: "/users", method: "GET" },
{ path: "/users", method: "POST" },
] as const satisfies readonly Route[];
type Method = (typeof routes)[number]["method"];
// "GET" | "POST"If a route uses an unsupported method, the declaration fails. The elements still retain their literal types.
`as const` Objects or Enums
A const object is often a simple alternative to an enum:
const Status = {
Active: "active",
Archived: "archived",
} as const;
type Status = (typeof Status)[keyof typeof Status];This emits an ordinary JavaScript object and keeps the type and values together. An enum provides enum-specific syntax and runtime behavior, so choose it when that behavior is useful. Prefer a const object when plain emitted JavaScript and easy interoperability are more important.
Const Type Parameters in Generic Functions
TypeScript 5.0 introduced const type parameters. They let a generic function infer literal and tuple types without requiring as const at every call site.
function tuple<const T extends readonly unknown[]>(items: T): T {
return items;
}
const pair = tuple(["id", 1]);
// readonly ["id", 1]The const modifier affects inference only. It does not freeze the argument at runtime.
Exercise
What is the main difference between as const and Object.freeze?
Show answer
as const changes only the compile-time type; Object.freeze also prevents property changes at runtime.