typescript-literales

Using Literals in TypeScript

  • 3 min

In TypeScript, literal types are types that allow defining variables with specific, predefined values instead of broad types like string or number.

The main reason is to allow us greater control and safety over the values a variable can take, limiting the available options.

String Literal Types

String literal types allow defining a variable that can only have one of several specific string values.

type Direction = "north" | "south" | "east" | "west";

let direction: Direction;

direction = "north"; // Correct
direction = "south"; // Correct
// direction = "northeast"; // Error: Type '"northeast"' is not assignable to type 'Direction'.
Copied!

Numeric Literal Types

Similar to string literals, numeric literal types allow a variable to have only certain specific numeric values.

type OneToTen = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;

let number: OneToTen;

number = 1;  // Correct
number = 5;  // Correct
// number = 11; // Error: Type '11' is not assignable to type 'OneToTen'.
Copied!

Literals and Union Types

Literal types are frequently used together with union types to create variables that can accept several specific values.

type Answer = "yes" | "no" | "maybe";

function respond(answer: Answer): void {
    console.log(`The answer is: ${answer}`);
}

respond("yes");      // Correct
respond("no");       // Correct
respond("maybe");    // Correct
// respond("perhaps"); // Error: Type '"perhaps"' is not assignable to type 'Answer'.
Copied!

Literals and Custom Types

Literal types can also be used in the definition of more complex custom types, providing greater control over object property values.

type Status = "started" | "in progress" | "completed";

interface Task {
    title: string;
    description: string;
    status: Status;
}

let task: Task = {
    title: "Learn TypeScript",
    description: "Study literal types in TypeScript.",
    status: "in progress"
};

// task.status = "pending"; // Error: Type '"pending"' is not assignable to type 'Status'.
Copied!

Template Literals

TypeScript supports template literals to create string literal types from combinations of other literal types.

type Prefix = "Mr." | "Mrs." | "Miss.";
type FullName = `${Prefix} ${string}`;

let person1: FullName = "Mr. Luis Pérez";
let person2: FullName = "Mrs. Ana Gómez";
// let person3: FullName = "Doctor Luis Pérez"; // Error: Type '"Doctor Luis Pérez"' is not assignable to type 'FullName'.
Copied!

Using Constant Literals

When appropriate, use constant literals to define specific values that should not change.

const ACTIVE_STATUS = "active";
const INACTIVE_STATUS = "inactive";

type Status = typeof ACTIVE_STATUS | typeof INACTIVE_STATUS;

let userStatus: Status = ACTIVE_STATUS;
Copied!

Practical Examples