Back

TypeScript Literal Type

Literal types restrict variables to specific constant values, increasing safety. They apply to strings, numbers, and booleans.

How to Define Literal Types

let direction: "left" | "right";
direction = "left";

The variable 'direction' only accepts 'left' or 'right'. Other values cause compile-time errors, preventing mistakes.

Using Literals in Function Parameters

function setTheme(mode: "light" | "dark") {
  console.log("Theme mode:", mode);
}

Literal types ensure only allowed values in parameters, useful for themes, directions, and roles.

Literal Types as Enum Alternatives

type Role = "admin" | "editor" | "viewer";

Literal unions defined with 'type' provide a simpler alternative to enums for small fixed value lists.

Boolean Literal Types

let isActive: true;
isActive = true;

Literal types are also used for boolean literals, restricting values to true or false explicitly.

Why Use Literal Types?

Literal types make code more predictable and safe, reducing errors and improving teamwork, especially in forms and API validation.

Back