Literal Types
TypeScript literal types let a type be one exact value instead of a whole category. You can say a variable must be "left" or "right", not just any string. This makes your code more precise and catches mistakes that a general string type would miss. In real projects, literal types power config options, alignment settings, and API response codes.
This tutorial covers string, numeric, and boolean literals, combining them into unions, why let widens a literal and const does not, const assertions with as const, and template literal types. You will also see how literal types compare to enums.
What Are TypeScript Literal Types?
A TypeScript literal type is a type that accepts only one exact value. Instead of string, you write "left". Instead of number, you write 42. The compiler then rejects any other value. Literal types are the building blocks of precise unions.
Here is a simple example:
const direction: "left" = "left";
console.log(direction);
// Output: left
The variable can hold only the string "left". Assigning "right" would be a compile error. This is useful when a value has a small, fixed set of options.
What Are String, Numeric, and Boolean Literal Types?
A literal type can be a string, a number, or a boolean. Each one pins the value to that exact literal. You rarely use a single literal alone; they become powerful when combined.
const method: "GET" = "GET";
const port: 8080 = 8080;
const enabled: true = true;
console.log(method, port, enabled);
// Output: GET 8080 true
How it works: method accepts only the string "GET", port accepts only the number 8080, and enabled accepts only true. These single-literal types are valid but limited. Their real value appears when you combine several literals into a union, covered next.
How Do You Combine Literals into a Union?
A union of literals is the most common use. You list the allowed values with the | operator. The compiler then checks that every assignment uses one of those exact values. This is how you model settings like text alignment, modes, or statuses.
type Align = "left" | "right" | "center";
function setAlign(value: Align): void {
console.log(`Aligning to ${value}`);
}
setAlign("left");
setAlign("center");
// setAlign("top");
// Error: Argument of type '"top"' is not assignable to parameter of type 'Align'.
// Output: Aligning to left
// Output: Aligning to center
How it works: The Align type lists three allowed strings. The setAlign function accepts only those three. Calling it with "top" produces a compile error before the code runs. In the editor, you get autocomplete for the three options, which reduces typos. You can learn more union patterns in the Type Aliases & Union Types tutorial.
Why Does let Widen and const Not?
When you assign a literal to a let variable, TypeScript widens the type to the general form, like string. When you use const, the type stays as the exact literal. This difference matters when you pass the value to a function that expects a literal union.
let loose = "left"; // inferred as string (widened)
const fixed = "left"; // inferred as "left" (literal)
function move(direction: "left" | "right"): void {
console.log(`Moving ${direction}`);
}
move(fixed);
// move(loose);
// Error: Argument of type 'string' is not assignable to parameter of type '"left" | "right"'.
// Output: Moving left
How it works: Because loose is declared with let, TypeScript assumes it may change, so it widens the type to string. Passing loose to move fails because string is too broad for the literal union. fixed stays as "left", which fits. This is why you should prefer const when the value will not change.
How Do const Assertions Work with Objects and Arrays?
A const assertion uses as const to tell TypeScript to treat every property or element as a readonly literal. This is useful for config objects and fixed lists, where you want the exact strings preserved. Without as const, object properties are widened to string.
const config = {
align: "left",
theme: "dark",
retries: 3,
} as const;
// config.align = "right";
// Error: Cannot assign to 'align' because it is a read-only property.
function setAlign(value: "left" | "right" | "center"): void {
console.log(value);
}
setAlign(config.align);
// Output: left
How it works: as const makes every property readonly and keeps each value as its literal type. So config.align is "left", not string. That means it can be passed directly to setAlign without any cast. Without as const, config.align would be string and the call would fail. The same works for arrays: const colors = ["red", "green"] as const; gives a readonly tuple of literal types.
What Are Template Literal Types?
A template literal type builds a new string literal type using a pattern, similar to JavaScript template strings but at the type level. You write it with backticks and ${}. It is useful for IDs, event names, and CSS class names where the pattern is fixed.
type UserId = `${string}-id`;
function loadUser(id: UserId): void {
console.log(`Loading ${id}`);
}
loadUser("riya-id");
loadUser("arjun-id");
// loadUser("riya");
// Error: Argument of type '"riya"' is not assignable to parameter of type '`${string}-id`'.
// Output: Loading riya-id
// Output: Loading arjun-id
How it works: The template literal type `${string}-id` means "any string that ends with -id." The compiler checks this at type level, so "riya-id" passes and "riya" fails. You can combine multiple parts, such as `${"click" | "hover"}-${string}`, to generate many allowed combinations from a small definition. This feature is available in TypeScript 4.1 and later.
Literal Types vs Enums: How Do They Compare?
| Feature | Literal Union | Enum |
|---|---|---|
| Runtime code | None | Generates an object |
| Readability | Good for short lists | Named members |
| Reverse mapping | Not available | Numeric enums only |
Works with isolatedModules |
Yes | Yes for regular enums |
| Adding a case | Edit the union | Add a member |
| Best for | Small sets, config values | Named constants, legacy code |
A practical recommendation: use a literal union for small sets of strings, such as alignment or mode. Use an enum when you want named constants, need reverse mapping, or are working in a codebase that already uses them. The TypeScript Enums tutorial covers enums in depth.
Common Mistakes and Best Practices
- Using
letwhen you need a literal type.letwidens the type tostring, so the value no longer fits a literal union. Useconstwhen the value will not change, or addas constto preserve the literal. - Forgetting
as conston config objects. Without it, every property widens tostringornumber, so you cannot pass values to functions that expect literal unions. Addas constto keep the exact types. - Making a literal union too large. A union of 30 strings is hard to read. Group related values into named aliases or switch to an enum for large sets.
- Assuming template literal types are available in older TypeScript. They require TypeScript 4.1 or later. If you are on an older version, the syntax will fail. Check your
package.jsonversion before relying on them. - Trying to mutate a value typed with
as const. Const assertions make propertiesreadonly, so assignment fails. If you need mutation, copy the object into a new variable with a wider type.
Real-World Example: A Layout Config
This example combines a literal union for alignment, an as const config object, and a template literal type for a class name.
type Align = "left" | "right" | "center";
type AlignClass = `text-${Align}`;
const layout = {
align: "center",
padding: 8,
theme: "light",
} as const;
function alignClass(align: Align): AlignClass {
return `text-${align}`;
}
function applyLayout(config: typeof layout): void {
const cls = alignClass(config.align);
console.log(`Class: ${cls}, padding: ${config.padding}`);
}
applyLayout(layout);
// Output: Class: text-center, padding: 8
// const bad = { align: "top" } as const;
// applyLayout(bad);
// Error: Argument of type '{ readonly align: "top"; }' is not assignable to parameter of type ...
How it works, line by line. The Align type lists three allowed strings. The AlignClass type is a template literal type that builds "text-left", "text-right", or "text-center" from any Align. The layout object uses as const, so align is the literal "center", padding is 8, and theme is "light", all readonly. The alignClass function accepts an Align and returns an AlignClass. The applyLayout function accepts a config of type typeof layout, so it expects the exact shape. It calls alignClass(config.align) and prints the result. The commented block shows the error you get when you pass "top": it does not fit Align, so the compiler rejects it. This combination of literal unions, as const, and template literal types gives you precise, self-checking code.
Summary
- TypeScript literal types accept one exact value, such as
"left",42, ortrue. - Combine literals into a union with
|to model a fixed set of allowed values. letwidens a literal to its general type, whileconstkeeps the exact literal.- A const assertion with
as constpreserves literal types and marks propertiesreadonly. - Template literal types build patterns like
`${string}-id`to restrict string shapes. - Use literal unions for small string sets and enums for larger named constant sets.
Now that you can pin down exact values, continue to the Functions in TypeScript tutorial to learn how to type parameters, return values, and optional arguments cleanly.
Frequently Asked Questions
What is the difference between a literal type and a regular type?
A regular type like string accepts any string. A literal type like "left" accepts only that exact string. Literal types are narrower and catch mistakes earlier, but they only make sense when the set of allowed values is small and fixed. Use them for config values, modes, and statuses.
Why does my const variable lose its literal type when I pass it to a function?
Because the function parameter may expect a general type like string, which widens your literal at the call site. To preserve the literal, annotate the parameter with a literal union, or use as const on the value. The compiler chooses the narrowest type that satisfies both sides.
Can I use template literal types with numbers?
Yes. Template literal types can include number, bigint, and boolean in the ${} slots. For example, `id-${number}` accepts strings like "id-42". The compiler treats the slot as a placeholder for that type. This is useful for IDs and versioned keys.
Does as const work on function return values?
No. as const applies to expressions like object literals, array literals, and string or number literals. You cannot write return x as const to change a function's return type in general. Instead, annotate the return type explicitly with the literal or union you need.
Practice Exercises
Exercise 1 (Easy): Create a Literal Union
Create a type Size = "small" | "medium" | "large". Write a function that accepts a Size and prints a message. Call it with two valid values.
Show solution
type Size = "small" | "medium" | "large";
function pickSize(size: Size): void {
console.log(`Selected ${size}`);
}
pickSize("small");
pickSize("large");
// Output: Selected small
// Output: Selected large
The Size union limits the argument to three strings, so "tiny" would be a compile error.
Exercise 2 (Easy): Use as const
Create a theme object with color: "blue" and mode: "dark" using as const. Pass theme.mode to a function that accepts "dark" | "light".
Show solution
const theme = { color: "blue", mode: "dark" } as const;
function setMode(mode: "dark" | "light"): void {
console.log(`Mode: ${mode}`);
}
setMode(theme.mode);
// Output: Mode: dark
Without as const, theme.mode would be string and fail. With it, the type is "dark", which fits the union.
Exercise 3 (Medium): Template Literal Type for Events
Create a template literal type ClickEvent = click-${"left" | "right"}``. Write a function that accepts a ClickEvent and prints it. Try both valid values.
Show solution
type ClickEvent = `click-${"left" | "right"}`;
function handleEvent(event: ClickEvent): void {
console.log(`Handled ${event}`);
}
handleEvent("click-left");
handleEvent("click-right");
// Output: Handled click-left
// Output: Handled click-right
The template literal type expands to "click-left" | "click-right", so any other string fails at compile time.
Exercise 4 (Challenge): Config Object with as const and a Literal Function
Create a config object with align: "center", retries: 3, and label: "submit" using as const. Write a function describe(config) that accepts the object type and returns a string using a template literal type Label = label-${string}``.
Show solution
const config = { align: "center", retries: 3, label: "submit" } as const;
type Label = `label-${string}`;
function describe(c: typeof config): Label {
return `label-${c.label}`;
}
console.log(describe(config));
// Output: label-submit
as const preserves each property as a literal and marks the object readonly, and the template literal type ensures the returned string starts with label-.
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts.
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
