Literal types, enums and as const
Course contents (16 lessons)
- Getting started
- Why TypeScript? What it is and what it is not
- Setting up TypeScript: tsc and tsconfig.json
- Core types
- Basic types: primitives, arrays, tuples, any and unknown
- Typing functions: parameters, returns, optionals and overloads
- Objects, interfaces and type aliases
- Unions, literals and enums
- Union types and type narrowing
- Literal types, enums and as const
- Classes and generics
- Classes in TypeScript
- Generics: writing reusable typed code
- Built-in utility types: Partial, Pick, Omit, Record and more
- Advanced types
- Mapped and conditional types
- Modules, type imports and declaration files
- TypeScript in real projects
- Typing async code and API responses
- Strict mode and compiler flags that matter
- Migrating a JavaScript project to TypeScript
- Final project: a type-safe task manager
Literal types
A literal type is a type with exactly one value. The string "north" is a type, the number 3 is a type, and so is true.
let answer: 42 = 42;
// answer = 43; // Error: Type '43' is not assignable to type '42'
type Method = "GET" | "POST" | "PUT" | "DELETE";
function request(url: string, method: Method): string {
return `${method} ${url}`;
}
console.log(request("/users", "GET"));
// request("/users", "FETCH"); // Error
A union of literals limits a value to a small set of options. The editor autocompletes the options for you, and typos become compile errors. For a configuration with a few choices, this is simple and effective.
A trap with widening
When you use let or an object property, TypeScript widens a literal to its general type:
const a = "GET"; // type "GET"
let b = "GET"; // type string
const config = { method: "GET" }; // method is string, not "GET"
// request("/x", config.method); // Error: string is not assignable to Method
console.log(a, b, config.method);
A const keeps the literal. A property in an object does not, because the property could be changed later. There are two fixes: annotate the object, or use as const.
as const
as const tells TypeScript to treat a value as deeply read-only and to keep every literal exactly.
const config = {
method: "GET",
retries: 3,
headers: ["json", "gzip"],
} as const;
type Method = "GET" | "POST";
function request(url: string, method: Method): string {
return `${method} ${url}`;
}
console.log(request("/x", config.method)); // works: method is "GET"
// config.retries = 4; // Error: read-only
console.log(config.headers[0]); // type is "json"
as const is the standard way to create a fixed list or lookup table where you want precise types.
Deriving a union from an array or an object
Here is a pattern I use constantly. You define the values once, and the type follows from them:
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number]; // "admin" | "editor" | "viewer"
function canEdit(role: Role): boolean {
return role === "admin" || role === "editor";
}
console.log(canEdit("editor")); // true
console.log(ROLES.includes("viewer")); // true
// canEdit("guest"); // Error
typeof ROLES gives the type of the array, and [number] means "the type of any item". You can loop over ROLES at runtime to build a dropdown, and the type always stays in sync.
For an object:
const Status = {
Active: "active",
Suspended: "suspended",
Deleted: "deleted",
} as const;
type Status = (typeof Status)[keyof typeof Status]; // "active" | "suspended" | "deleted"
const current: Status = Status.Active;
console.log(current);
The same name Status is used for the value and the type. TypeScript keeps values and types in separate worlds, so this is allowed and common.
Enums
TypeScript also has a built-in enum keyword. It was added before JavaScript had modules, and it exists in two forms.
Numeric enums count up from zero by default:
enum Direction {
Up, // 0
Down, // 1
Left, // 2
Right, // 3
}
const d: Direction = Direction.Left;
console.log(d); // 2
console.log(Direction[2]); // "Left" (reverse mapping)
String enums give each member a text value:
enum LogLevel {
Debug = "DEBUG",
Info = "INFO",
Error = "ERROR",
}
function log(level: LogLevel, message: string): void {
console.log(`[${level}] ${message}`);
}
log(LogLevel.Info, "Server started");
// log("INFO", "x"); // Error: a plain string is not accepted
Unlike a literal union, an enum is a real object that exists at runtime. The compiler generates code for it.
Enums or unions?
Numeric enums have a known weakness: in older versions any number could be assigned to them, so const d: Direction = 99 compiled. Newer versions check this, but enums still behave differently from the rest of the language. They generate runtime code, they do not work with tools that only strip types (such as Node's built-in type stripping, which rejects enums), and string enums are not interchangeable with plain strings.
For these reasons, many teams now prefer unions of string literals, or as const objects, for most uses. They produce no extra JavaScript, accept plain strings, and are easier to read in logs and JSON. My advice:
- Default to a literal union or an
as constobject. - Use a string enum if the code base already uses them, or if you want the nominal strictness that a plain string does not give.
- Avoid numeric enums, unless you need bit flags or to match a protocol.
TypeScript 5.8 added the compiler option erasableSyntaxOnly, which rejects enums, among a few other features. Use it if you want your code to be compatible with plain type stripping.
Template literal types
Literal types can be combined into new ones with the same syntax as template strings:
type Side = "top" | "bottom";
type Edge = `margin-${Side}`; // "margin-top" | "margin-bottom"
const m: Edge = "margin-top";
console.log(m);
You will see these in libraries for event names and CSS property types.
Common mistakes
- Expecting an object property to keep its literal. Use
as constor an annotation. - Passing a plain string to a string enum. It is an error, and a literal union would have accepted it.
- Using numeric enums for readability. Logging
2tells you nothing. - Duplicating a list of values and a union type. Derive the type from the array.
- **Forgetting
as conston a lookup table.** The values widen tostring.
Try it yourself
- Create a
type Size = "small" | "medium" | "large"and a function that returns a price for each size. - Make an
as constarray of weekdays and derive aWeekdaytype from it. - Define a string enum
OrderStatusand a function that returns a label for each member. Rewrite it with a literal union. - Create a type
EventNameusing a template literal type, for example"on" + Capitalize<"click" | "hover">.
const config = {
method: "GET",
retries: 3,
headers: ["json", "gzip"],
} as const;
type Method = "GET" | "POST";
function request(url: string, method: Method): string {
return `${method} ${url}`;
}
console.log(request("/x", config.method)); // works: method is "GET"
// config.retries = 4; // Error: read-only
console.log(config.headers[0]); // type is "json"
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account