Sub topic 1
Literal types: types that hold exactly one value
A literal type is a type that accepts exactly one value. The type "up" accepts the string "up" and nothing else. The type 42 accepts the number 42. This chapter covers what literal types are, where they come from, how they relate to string and number, and which mistakes they cause. The chapters that follow build on them with unions, enums and as const.
Prerequisites
This chapter assumes you already know the following:
- The basic TypeScript types
string,number,booleanand object types. - How to annotate variables, parameters and return types.
- Plain JavaScript
constandlet, and the strict equality operator===.
Turn on strict in your tsconfig.json to reproduce the error messages shown here. Without strict, some of these checks are weaker.
From a general type to a single value
The type string describes an infinite set of values. A literal type shrinks that set to one member. You write it by using the value itself in a type position.
const direction: "up" = "up";
let answer: 42 = 42;
let enabled: true = true;Each variable can only ever hold its own value. Reassignment to anything else is a compile error, even for a let.
let mode: "dark" = "dark";
mode = "light"; // Error: Type '"light"' is not assignable to type '"dark"'.Read "dark" in a type position as "the set that contains only the string dark". A literal type is therefore a subtype of its base type. Every "dark" is a string, but not every string is "dark".
The kinds of literal types
TypeScript has literal types for four kinds of primitive values.
| Kind | Example type | Example value | Notes | Column |
|---|---|---|---|---|
| String | `"GET"` | `"GET"` | Case sensitive. `"get"` is a different type. | |
| Number | `404`, `-1` | `404` | Negative numbers are allowed. | |
| Boolean | `true`, `false` | `true` | `boolean` is the union `true \ | false`. |
| BigInt | `100n` | `100n` | Needs a compile target of ES2020 or later. |
Other primitives are already single-valued types. null and undefined each have exactly one value, so they behave like literal types. Symbols can also produce a single-value type, called a unique symbol. That case is rare and outside this chapter.
Template strings without substitutions work as string literal types in value positions. In type positions you cannot write a backtick string that interpolates other types as if it were a plain literal. That feature is called a template literal type and has its own chapter.
Direction of assignability
Assignability between a literal and its base type goes one way. A literal can flow into the wider type, but the wider type cannot flow back into the literal.
const small: "up" = "up";
const wide: string = small; // OK: "up" is a string
let text: string = "up";
const narrow: "up" = text; // Error: Type 'string' is not assignable to type '"up"'.The second error surprises many people, because text holds "up" right now. The compiler checks the declared type of text, which is string, and not the value it was last given. This is the reason literal types matter in practice. A function that asks for "up" rejects a general string, because the compiler cannot prove which string it holds.
Narrowing can recover the information. After a check such as text === "up", the compiler treats text as "up" inside the if block.
function handle(text: string): void {
if (text === "up") {
const direction: "up" = text; // OK: narrowed by the comparison
console.log(direction);
}
}Literals in function signatures
The most common use of a literal type is on a parameter. It turns a mistake that would happen at runtime into an error at compile time.
function setPrecision(digits: 2 | 4 | 8): string {
return Math.PI.toFixed(digits);
}
console.log(setPrecision(4)); // "3.1416"
setPrecision(3); // Error: Argument of type '3' is not assignable to parameter of type '2 | 4 | 8'.The 2 | 4 | 8 syntax combines literals into a union. Unions get a full treatment in the next chapter. For now, read the | as "or".
A literal return type also documents behavior and lets callers rely on it.
function alwaysTrue(): true {
return true;
}
const result = alwaysTrue(); // type: trueReturn types need an explicit annotation. When you leave it off, TypeScript widens a single literal return value to its base type.
function inferred() {
return "ok";
}
function annotated(): "ok" {
return "ok";
}
const a = inferred(); // type: string
const b = annotated(); // type: "ok"If you want callers to see "ok", write the return type.
Booleans are literal unions
The boolean type is shorthand for the union true | false. This explains several behaviors that look odd at first.
function describe(flag: boolean): string {
if (flag === true) {
return "yes";
}
// Here flag is narrowed to false
const rest: false = flag;
return rest ? "unreachable" : "no";
}
console.log(describe(false)); // "no"You can use true or false alone as a type when a value is fixed by contract. A common case is a configuration flag that must be on.
type StrictConfig = {
strict: true;
target: string;
};
const ok: StrictConfig = { strict: true, target: "es2022" };
const bad: StrictConfig = { strict: false, target: "es2022" };
// Error: Type 'false' is not assignable to type 'true'.Comparing with literals
Literal types make the compiler check comparisons. If two types cannot overlap, the comparison can never be true, and TypeScript reports it.
const status: 200 = 200;
if (status === 404) {
// Error: This comparison appears to be unintentional because the types '200' and '404' have no overlap.
}This check catches typos in string constants too. If a parameter has the type "success" | "failure", then comparing it to "sucess" fails to compile. With a plain string parameter, the typo would pass silently and the branch would never run.
Literals exist only at compile time
Literal types are erased when TypeScript compiles to JavaScript. Nothing about "up" as a type remains in the output. This has two consequences.
First, a literal type cannot validate data that arrives at runtime. Values from JSON.parse, form fields, query strings and network responses are typed as string or any. The annotation does not make them safe. You need a runtime check.
Second, you can write a type guard to connect the check to the type. A type guard is a function whose return type says "if I return true, this value has this type".
function isYes(value: string): value is "yes" {
return value === "yes";
}
function answer(input: string): void {
if (isYes(input)) {
const confirmed: "yes" = input; // OK: narrowed by the guard
console.log("Confirmed", confirmed);
} else {
console.log("Not confirmed");
}
}
answer("yes"); // Confirmed yes
answer("no"); // Not confirmedThe compiler trusts the guard. If you write a guard that returns true for the wrong values, the types will be wrong without any warning. Keep the check inside the guard simple and complete.
Where literals come from in inferred types
You do not always write literals yourself. TypeScript infers them in some places and widens them in others. The rules are subtle, and later chapters cover them in full, so here is the short version.
A const declaration of a primitive keeps the literal type, because the value can never change. A let declaration widens it to the base type, because the value might change later.
const fixed = "up"; // type: "up"
let loose = "up"; // type: stringProperties of object literals widen too, because properties are mutable by default.
type Request = { method: "GET" };
function send(request: Request): void {
console.log(request.method);
}
send({ method: "GET" }); // OK: the literal is checked against the expected type
const request = { method: "GET" };
send(request);
// Error: Argument of type '{ method: string; }' is not assignable to parameter of type 'Request'.
// Types of property 'method' are incompatible.The first call passes because the object appears directly where a Request is expected, so the compiler uses that expectation to keep "GET" as a literal. The second call fails because request was declared first. At that point nothing says method should be a literal, so it becomes string. This pattern is the most common literal-type error in real code. You can fix it by annotating the variable (const request: Request = ...) or by using as const, which a later chapter explains.
Common errors and how to read them
Most literal type errors fall into a few shapes. Learning to recognize them saves time.
- "Type 'string' is not assignable to type '"x"'": a wide value is flowing into a literal slot. Find where the value was declared and why it widened, or narrow it with a check.
- "Type '"x"' is not assignable to type '"y"'": you passed the wrong constant, often because of a typo or a case difference.
- "This comparison appears to be unintentional": you are comparing against a value that the type rules out. Either the type is too narrow or the comparison is wrong.
- An inferred
stringwhere you expected a literal: alet, a mutable property or an unannotated return type widened the value.
The error text often shows the literal in double quotes inside single quotes, such as '"light"'. The inner quotes are part of the type, so they tell you that TypeScript sees a literal and not a string.
When literal types are the wrong tool
A literal type fixes the value at compile time. Use it when the set of allowed values is small and known when you write the code. It is a poor fit in two cases.
- The set of values is open or comes from data, such as user names or IDs. A
stringwith runtime validation is the honest type. - You need the values to exist as runtime objects that you can list, iterate or look up in reverse. Types are erased, so a literal type alone gives you nothing to loop over. Enums and
as constobjects address this need, and the later chapters compare them.
Summary of the working model
A literal type is a one-value type that is a subtype of its base type. It flows into the wider type but not back. It is erased at runtime, so external data needs a check. Inference widens it in let declarations, mutable properties and unannotated return types. Most of the benefit comes when you combine several literals into a union, which is the topic of the next chapter.
Exercise
Given let text: string = "up"; and const narrow: "up" = text;, the compiler reports an error even though text holds "up". Why, and how can you make the assignment compile without changing the declaration of text?
Show answer
The compiler checks the declared type of text, which is string, and a string is not assignable to "up" because it could hold any string. Narrow the value first with a check such as if (text === "up") { const narrow: "up" = text; }, or use a type guard like function isUp(v: string): v is "up" { return v === "up"; }. Inside the narrowed block, text has the type "up".
Exercise
What are the types of a and b in function f() { return "ok"; }, const a = f(); and function g(): "ok" { return "ok"; }, const b = g();? Explain the difference.
Show answer
a has the type string and b has the type "ok". With no return type annotation, TypeScript widens a single literal return value to its base type. The explicit annotation "ok" on g keeps the literal type for callers.
Exercise
Why does send(request) fail below, while send({ method: "GET" }) compiles? Show one change that fixes the failing call.
type Request = { method: "GET" };
const request = { method: "GET" };
Show answer
The object request is declared without a contextual type, so its mutable property method widens to string, and { method: string } is not assignable to { method: "GET" }. In the direct call, the expected Request type keeps "GET" as a literal. Fix it by annotating the declaration: const request: Request = { method: "GET" };.