DevAcademy
LearnTypeScriptLiteral Types
BeginnerTypeScript

Literal Types

Learn how to restrict a value to one or more specific literal values instead of a broad type.

Reading Time

12 min

Lesson

Lesson 12 of 30

What is a Literal Type?

A literal type narrows a value down to one exact value rather than an entire category of values — "success" as a type means only the string "success" is allowed, not any string.

A String Literal Type

let direction: "up" | "down" | "left" | "right";

direction = "up";      // OK
direction = "sideways"; // Error: not assignable

Literal Types Also Work with Numbers and Booleans

Literal types aren’t limited to strings — number and boolean values can be narrowed to specific literals too.

Numeric and Boolean Literals

type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
type Toggle = true; // only the literal value true is allowed

let roll: DiceRoll = 4;
let alwaysOn: Toggle = true;

Literal Types as Function Parameters

A common use for literal unions is restricting a function parameter to a small, valid set of string options — similar in spirit to an enum, but with no extra runtime code.

Restricting a Parameter

function setAlignment(value: "left" | "center" | "right") {
  // ...
}

setAlignment("center"); // OK
setAlignment("middle");  // Error: not one of the allowed literals

const Narrows Automatically, let Does Not

A variable declared with const and a literal value is automatically inferred as that literal type, since it can never change. A let variable is inferred more broadly (as string, number, etc.) since it might be reassigned later.

const vs let Inference

const status = "active";  // inferred as the literal type "active"
let mutableStatus = "active"; // inferred more broadly as string

as const

The as const assertion locks an entire object or array to its most specific literal types, and makes it deeply readonly — extremely useful for defining constant configuration values.

as const Example

const config = {
  theme: "dark",
  version: 2,
} as const;

// config.theme is typed as "dark", not string
// config is also readonly — reassigning a property is an error

Best Practice

Use literal unions for small, closed sets of valid string/number values passed as parameters, and as const for defining fixed configuration objects whose exact shape and values should never change.

Interview Questions

Quick Quiz

1. What does the literal type "success" allow as a value?

2. How is a const string variable typically inferred, compared to a let variable?

3. What does the as const assertion do to an object?