Introduction to Literal Types
TypeScript normally allows broad types such as string, number, and boolean. Sometimes, however, an application should accept only a specific value rather than every value of a particular type.
Literal types make this possible by representing exact values. For example, the type "dark" represents the string value dark, while the type 200 represents the numeric value 200. A variable declared with one of these types can only receive a compatible value.
Literal types are particularly useful for application settings, supported commands, HTTP status values, component variants, workflow states, and other situations where only a defined set of values is valid.
You can combine literal types with union types, type aliases, const assertions, discriminated unions, and template literal types to describe application behavior more precisely. These features improve autocomplete, help catch invalid assignments, and make type contracts easier to understand.
1. Understanding String Literal Types
A string literal type represents one exact string value. Unlike the general string type, it does not allow arbitrary strings.
let direction: "north";
direction = "north";
// Compile-time error:
// direction = "south";
console.log(direction);
The direction variable can contain only the string north. Assigning south produces a type error because south is not compatible with the declared literal type.
This is useful when a value has only one valid representation at a particular point in your application. However, a single literal type can be restrictive if the value needs to change between several supported options.
For example, a theme setting might support light, dark, and system. A literal union allows all three valid choices without permitting unrelated values.
type Theme = "light" | "dark" | "system";
let selectedTheme: Theme = "dark";
selectedTheme = "light";
selectedTheme = "system";
// Compile-time error:
// selectedTheme = "blue";
console.log(selectedTheme);
Each literal in the union represents an accepted value. TypeScript checks assignments against this set and reports unsupported alternatives during development.
2. Numeric Literal Types
Numeric literal types restrict a value to an exact number. They are useful when an application supports a known collection of numeric options or identifiers with specific permitted values.
type HttpSuccessStatus = 200 | 201 | 204;
let statusCode: HttpSuccessStatus = 200;
statusCode = 201;
statusCode = 204;
// Compile-time error:
// statusCode = 404;
console.log(statusCode);
HttpSuccessStatus accepts only 200, 201, and 204. Other numbers, including 404 and 500, are rejected by the type checker.
Numeric literal types can also model fixed configuration values, menu choices, supported protocol versions, and limited scoring categories.
Do not restrict a value to a numeric literal union unless the set is genuinely limited. If a variable represents any valid temperature, price, or quantity, the broad number type is usually more appropriate.
3. Boolean Literal Types
Boolean literals are true and false. They can be used as types to express a specific state rather than allowing both boolean values.
type EnabledFeature = true;
type DisabledFeature = false;
const featureEnabled: EnabledFeature = true;
const featureDisabled: DisabledFeature = false;
// Compile-time error:
// const invalidFeature: EnabledFeature = false;
console.log(featureEnabled);
console.log(featureDisabled);
The type EnabledFeature allows only true, while DisabledFeature allows only false. These declarations can be useful in specialized type definitions and APIs where a state has a fixed boolean value.
In everyday application code, a literal boolean often becomes more useful as part of an object union. For example, a successful result might have success: true and contain data, while a failed result has success: false and contains an error message.
That structure allows TypeScript to connect a boolean state with the properties that are available for that state.
4. Literal Unions for Restricted Options
A literal union combines several exact values into one type. This is one of the most common and practical uses of literal types.
type ButtonVariant = "primary" | "secondary" | "danger";
function getButtonClass(variant: ButtonVariant): string {
switch (variant) {
case "primary":
return "button-primary";
case "secondary":
return "button-secondary";
case "danger":
return "button-danger";
}
}
console.log(getButtonClass("primary"));
console.log(getButtonClass("danger"));
// Compile-time error:
// getButtonClass("warning");
ButtonVariant limits the function to three supported variants. The function caller receives meaningful autocomplete suggestions and cannot accidentally pass an unsupported value without bypassing the type system.
Literal unions are suitable for dropdown options, sorting directions, application routes represented as names, supported languages, access levels, and component properties.
They also communicate intent clearly. A parameter typed as string accepts any string, while a parameter typed as ButtonVariant documents exactly which options the function supports.
5. Literal Type Inference and Type Widening
TypeScript can infer literal types automatically, but whether it retains a literal or widens it to a broader type depends on the declaration and its context.
const fixedTheme = "dark";
let changeableTheme = "dark";
// fixedTheme has type "dark".
// changeableTheme has type string.
changeableTheme = "light";
// Compile-time error:
// fixedTheme = "light";
console.log(fixedTheme);
console.log(changeableTheme);
A const variable initialized with a string literal normally retains the exact literal type because the variable cannot be reassigned. A let variable is intended to be reassigned, so TypeScript generally infers the broader string type.
Numeric values follow a similar pattern. A const variable initialized with 100 normally has the type 100, while a let variable initialized with 100 generally has the type number.
Type widening lets ordinary variables remain flexible without requiring developers to annotate every declaration. When you need a reusable variable that accepts several specific alternatives, explicitly declare its literal union type.
type Theme = "light" | "dark";
let selectedTheme: Theme = "dark";
selectedTheme = "light";
selectedTheme = "dark";
// Compile-time error:
// selectedTheme = "system";
console.log(selectedTheme);
Explicit annotations are particularly valuable for function parameters, object properties, and state variables where the accepted alternatives form an important part of the API.
6. Const Assertions with as const
A const assertion tells TypeScript to preserve literal information instead of widening literal values in the asserted expression. It also makes object properties readonly and turns array literals into readonly tuples.
const themeOptions = ["light", "dark", "system"] as const;
type Theme = typeof themeOptions[number];
const selectedTheme: Theme = "dark";
// Compile-time error:
// const invalidTheme: Theme = "blue";
// Compile-time error:
// themeOptions[0] = "dark";
console.log(themeOptions);
console.log(selectedTheme);
The as const assertion preserves the array as a readonly tuple of literal values. The type expression typeof themeOptions[number] extracts the union of its element types, resulting in "light" | "dark" | "system".
This pattern prevents a common inference problem. Without as const, TypeScript may infer a mutable array of strings, which would produce the broader element type string rather than the desired literal union.
Const assertions affect TypeScript's static type system; they do not automatically freeze the runtime array or object. If runtime immutability is required, use appropriate runtime mechanisms as well.
This technique is useful for defining supported routes, product categories, UI options, command names, and fixed configuration values without repeating the same literal union in multiple places.
7. Literal Types with Object Properties
Literal types can restrict individual object properties. This is especially useful when a field should contain one of a fixed set of values rather than any string or number.
type UserRole = "admin" | "editor" | "viewer";
interface User {
id: number;
name: string;
role: UserRole;
}
const user: User = {
id: 101,
name: "Asha",
role: "admin"
};
user.role = "editor";
// Compile-time error:
// user.role = "owner";
console.log(user.name);
console.log(user.role);
The role property only accepts admin, editor, or viewer. Other fields retain their broader types because they need to represent a larger range of values.
This is useful for models containing status, role, category, priority, or visibility fields. You can keep ordinary data flexible while strictly controlling the fields that have defined alternatives.
Literal types can also be used in type aliases that combine several object variants. A shared literal property can identify the particular variant and allow safe property access through narrowing.
8. Discriminated Unions with Literal Types
A discriminated union combines object types that share a property with different literal values. TypeScript uses that property to determine which object structure is present.
type SuccessResult = {
status: "success";
data: string;
};
type ErrorResult = {
status: "error";
message: string;
};
type ApiResult = SuccessResult | ErrorResult;
function handleResult(result: ApiResult): string {
if (result.status === "success") {
return "Loaded: " + result.data;
}
return "Failed: " + result.message;
}
console.log(handleResult({
status: "success",
data: "Course information"
}));
console.log(handleResult({
status: "error",
message: "Course not found"
}));
The status property uses the literal types success and error. When TypeScript sees status === "success", it narrows result to SuccessResult and allows access to data.
In the other branch, result is ErrorResult, so the message property is available. This avoids accessing a property that does not exist on every union member.
Literal discriminants are useful for API responses, loading states, authentication results, form submissions, and asynchronous workflows. They make the connection between a state and its associated data explicit.
For complex unions, exhaustive checking with never can help ensure that every alternative has been handled when the type is extended later.
9. Template Literal Types
Template literal types allow you to construct new string types from literal strings, unions, and other supported types. They use syntax similar to JavaScript template literals, but describe possible string values at the type level.
type Action = "created" | "updated" | "deleted";
type UserEvent = `user:${Action}`;
const eventOne: UserEvent = "user:created";
const eventTwo: UserEvent = "user:updated";
// Compile-time error:
// const invalidEvent: UserEvent = "user:archived";
console.log(eventOne);
console.log(eventTwo);
UserEvent combines the prefix user: with every member of Action. Its resulting type is the union "user:created" | "user:updated" | "user:deleted".
Template literal types are helpful for event names, namespaced keys, action identifiers, environment variable names, and structured strings whose format should be checked by TypeScript.
They can also use multiple unions. TypeScript forms combinations of the supplied possibilities, so the resulting union can grow quickly when each part contains many alternatives.
type Size = "small" | "large";
type Color = "blue" | "orange";
type ButtonStyle = `${Size}-${Color}`;
const first: ButtonStyle = "small-blue";
const second: ButtonStyle = "large-orange";
console.log(first);
console.log(second);
ButtonStyle allows the four combinations small-blue, small-orange, large-blue, and large-orange. Combinations outside those possibilities are rejected.
10. Using satisfies with Literal Types
The satisfies operator checks whether an expression conforms to a type without replacing the expression's inferred type with that target type. It is helpful when creating configuration objects that need validation while retaining useful literal information.
type Theme = "light" | "dark";
type AppConfig = {
theme: Theme;
debug: boolean;
};
const config = {
theme: "dark",
debug: true
} as const satisfies AppConfig;
console.log(config.theme);
console.log(config.debug);
// Compile-time error:
// const invalidConfig = {
// theme: "blue",
// debug: true
// } as const satisfies AppConfig;
The expression is checked against AppConfig, so TypeScript rejects an unsupported theme or an incorrectly typed debug value. At the same time, as const preserves the exact literal values and marks the properties readonly in the inferred type.
Without as const, satisfies does not automatically make every property of a mutable object literal into a literal type. For example, a property initialized with dark may still be inferred as string when the resulting object property is mutable. The const assertion deliberately preserves the literal value.
Use satisfies when you want to validate a value against a contract while keeping useful details from its inferred type. It is especially effective for configuration objects, lookup tables, and static application settings.
11. Literal Types with Function Overloads and APIs
Literal types can make APIs more precise by restricting the options a function accepts. A function can also use literal alternatives to associate particular inputs with predictable behavior.
type SortDirection = "ascending" | "descending";
function sortNumbers(
values: number[],
direction: SortDirection
): number[] {
const result = [...values];
result.sort((a, b) => {
return direction === "ascending" ? a - b : b - a;
});
return result;
}
console.log(sortNumbers([8, 2, 5], "ascending"));
console.log(sortNumbers([8, 2, 5], "descending"));
// Compile-time error:
// sortNumbers([8, 2, 5], "random");
SortDirection describes the supported sorting options. The function cannot be called with an arbitrary string, so callers must use one of the declared directions.
The implementation creates a copy before sorting, preventing it from changing the caller's original array. The literal union controls the option, while ordinary number and array types describe the data being processed.
This pattern is common in component APIs, utility functions, query builders, logging systems, and libraries where users select among a finite number of behaviors.
12. Common Mistakes with Literal Types
Using a broad type when only specific values are valid
A string property accepts arbitrary strings. If an application supports only a few options, define a literal union instead so unsupported values are caught during type checking.
Expecting a let variable to retain its literal type
A mutable variable initialized with a string or number literal normally widens to the broader type. Use an explicit literal union annotation when the variable should support only selected values.
Forgetting as const for literal collections
A normal array of strings may infer string as its element type. A const assertion can preserve the individual literal values and create a readonly tuple.
Confusing compile-time restrictions with runtime validation
Literal types do not validate network responses, user input, or parsed JSON at runtime. Check external values before trusting them as one of the permitted alternatives.
Using assertions to silence invalid assignments
Type assertions can bypass useful checks without changing the actual runtime value. Prefer validating or correcting the source value rather than asserting that it has a literal type it may not satisfy.
Creating unnecessarily large template literal unions
Combining several large unions can produce many possible string combinations. Keep template literal patterns focused and consider simpler types when the resulting union becomes difficult to maintain.
Best Practices for Literal Types
- Use literal unions when a variable, parameter, or property supports a fixed set of valid values.
- Prefer descriptive type aliases such as Theme, SortDirection, and UserRole instead of repeating long unions.
- Use ordinary string, number, or boolean types when values genuinely need unrestricted flexibility.
- Understand type widening and explicitly annotate mutable variables when they should retain a limited set of alternatives.
- Use as const when fixed arrays and objects should preserve literal values and readonly type information.
- Use typeof and indexed access types to derive unions from existing constant collections.
- Use discriminated unions when literal fields identify alternative object structures.
- Use template literal types for predictable string patterns, such as event names or namespaced identifiers.
- Use satisfies to check configuration objects against an expected type without unnecessarily replacing their inferred types.
- Validate untrusted runtime values instead of relying only on compile-time annotations.
Conclusion
Literal types let TypeScript represent exact values instead of broad categories. They help restrict application settings, function arguments, object properties, statuses, and other fields to the alternatives that are actually supported.
Literal unions make these restrictions reusable, while const assertions preserve literal information in static collections and template literal types construct strings from known patterns. Discriminated unions use literal properties to identify different object structures and support safer control flow.
Practise defining literal unions, extracting types from readonly collections, narrowing discriminated unions, and validating configuration objects with satisfies. These techniques make TypeScript contracts more precise, provide better editor assistance, and help prevent invalid values from entering your application through ordinary typed code.