Basic · 8 of 13 · 13 min read
Literal types and as const
A single value as a type, why let and object properties lose it, and the as const pattern that derives a union from real data.
- Literal types
A literal type is a type with exactly one value in it. On its own that is a curiosity; in a union it is how you say “one of these three strings” and have the compiler hold you to it.
A value as a type
let exact: "GET" = "GET";
// exact = "POST"; // Type '"POST"' is not assignable to type '"GET"'
type Method = "GET" | "POST" | "DELETE";
type Bit = 0 | 1;
type Flag = true;
const m: Method = "POST";
// const bad: Method = "PATCH"; // not assignable
console.log(m);
The payoff is three things at once: autocomplete in the editor, a compile error for a typo, and exhaustiveness when you switch over it.
type Status = "success" | "error" | "loading";
function render(status: Status): string {
switch (status) {
case "success": return "Done";
case "error": return "Failed";
case "loading": return "…";
}
}
console.log(render("success")); // "Done"
// Adding a member to Status makes this function a compile error until handled.
All of it is compile time. A string arriving from an API is still just a string:
const fromApi: string = "ready";
// const bad: Status = fromApi; // 'string' is not assignable to 'Status'
Widening
let a = "hello"; // string
const b = "hello"; // "hello"
A let can be reassigned, so the compiler generalises. A const cannot, so it keeps the exact
value. Object properties widen for the same reason — const fixes the binding, not the contents:
type Method = "GET" | "POST";
const config = { method: "GET" }; // method: string
function send(method: Method) {}
// send(config.method); // 'string' is not assignable to 'Method'
Three fixes, in rough order of preference:
type Method = "GET" | "POST";
function send(method: Method) {}
const a = { method: "GET" } as const; // method: "GET"
const b: { method: Method } = { method: "GET" }; // annotate the object
const c = { method: "GET" as Method }; // assert the property
send(a.method);
send(b.method);
send(c.method);
console.log(a.method);
| Written as | Inferred |
|---|---|
let x = "a" |
string |
const x = "a" |
"a" |
{ x: "a" } |
{ x: string } |
{ x: "a" } as const |
{ readonly x: "a" } |
["a", "b"] |
string[] |
["a", "b"] as const |
readonly ["a", "b"] |
as const
It does two things at once: every member becomes readonly, and every value keeps its literal
type — recursively.
const roles = ["admin", "user"] as const;
// readonly ["admin", "user"]
// roles.push("guest"); // push does not exist on a readonly tuple
console.log(roles[0], roles.length); // "admin" 2
const config = {
retries: 3,
endpoints: { users: "/users" },
} as const;
// { readonly retries: 3; readonly endpoints: { readonly users: "/users" } }
// config.endpoints.users = "/x"; // Cannot assign — deep, unlike Object.freeze
console.log(config.endpoints.users);
Note the contrast with Object.freeze, which is shallow and runtime; as const is deep and
compile-time only.
Deriving the union from the data
The most useful pattern on this page. When you need the values at runtime anyway — for a dropdown, for validation — derive the type from the array instead of writing both:
const STATUSES = ["draft", "published", "archived"] as const;
type Status = (typeof STATUSES)[number]; // "draft" | "published" | "archived"
function isStatus(value: string): value is Status {
return (STATUSES as readonly string[]).includes(value);
}
const fromApi = "draft";
if (isStatus(fromApi)) {
const s: Status = fromApi;
console.log(s); // "draft"
}
console.log(STATUSES.join(", ")); // for the dropdown
One list. Adding "deleted" to it extends the type and the dropdown together, and there is no
second place to forget.
The same works for an object:
const ROLES = { admin: "admin", user: "user" } as const;
type Role = (typeof ROLES)[keyof typeof ROLES]; // "admin" | "user"
const r: Role = ROLES.admin;
console.log(r, Object.keys(ROLES));
That pattern is also the usual replacement for an enum: same autocomplete, same exhaustiveness, nothing emitted, and the values are plain strings that come straight out of JSON.
Literal types are not only strings
type Bit = 0 | 1;
type Dice = 1 | 2 | 3 | 4 | 5 | 6;
type Answer = true | false; // the same as boolean
type Big = 1n | 2n;
function roll(): Dice { return 4; }
console.log(roll() > 3); // true
And they combine with template literal types to build sets without listing them:
type Size = "sm" | "lg";
type Variant = "primary" | "ghost";
type ClassName = `btn-${Variant}-${Size}`;
// "btn-primary-sm" | "btn-primary-lg" | "btn-ghost-sm" | "btn-ghost-lg"
const c: ClassName = "btn-ghost-lg";
console.log(c);
Where widening is what you want
Not every literal should be preserved. A counter that starts at zero is a number, not a 0:
let count = 0; // number — correct, it is going to change
count += 1;
const MAX = 100; // 100 — also correct, it never changes
console.log(count, MAX);
The rule falls out of the keyword: const means “this value, forever”, and the type says so.
Common mistakes
Expecting an object property to keep its literal
Mistake. const config = { method: "GET" } passed where "GET" | "POST" is expected.
Why it fails. const fixes the binding, not the property — which is mutable, so its type is
widened to string.
What to do instead. as const on the object, or annotate it.
Writing the union and the array separately
Mistake. type Role = "admin" | "user" next to const ROLES = ["admin", "user"].
Why it fails. Two lists to keep in step, and nothing checks that they agree.
What to do instead. One as const array, and (typeof ROLES)[number] for the type.
Using as where as const was meant
Mistake. const config = { method: "GET" } as Config to make an error go away.
Why it fails. A type assertion overrides the compiler and checks nothing. as const asks it
to be more precise, and checks everything.
What to do instead. as const for precision, satisfies when you also want conformance
checked.
Check yourself
4 questions from the bank on what you just read. Answering here does not affect your quiz history.
What does a literal union like "success" | "error" | "loading" give you?
Object properties are mutable by default, so the compiler widens their literal types.
Why does passing config.method fail?
type Method = "GET" | "POST";
const config = { method: "GET" };
function send(method: Method) {}
send(config.method);as const turns a mutable structure into a deeply readonly one of literal types.
What is the inferred type of roles?
const roles = ["admin", "user"] as const;What is the advantage of deriving a union from a const array over writing it by hand?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.