TypeScript Literal Types (original) (raw)

Last Updated : 9 Sep, 2025

TypeScript's literal types allow developers to specify exact values for variables, function parameters, or properties, enhancing type safety by ensuring variables can only hold predefined values.

Types of literal types

Here are the different types of literal types:

1. String Literal Types

String literal types allow a variable to accept only a specific set of string values.

JavaScript `

type Direction = "Up" | "Down" | "Left" | "Right";

let move: Direction;

move = "Up"; // move = "Forward";

`

**Output:

Up Error: Type '"Forward"' is not assignable to type 'Direction'

**In this example:

**2. Numeric Literal Types

Numeric literal types restrict a variable to a specific set of numeric values..

JavaScript `

type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;

function rollDice(): DiceRoll { return 4; // Valid // return 7; Error }

console.log(rollDice());

`

**Output :

4 Error: Type '7' is not assignable to type 'DiceRoll'

**In this example:

3. Boolean Literal Types

Boolean literal types constrain a variable to the boolean values true or false.

JavaScript `

type Success = true;

function operation(): Success { return true; // Valid return value // return false; // Error } console.log(operation());

`

**Output:

true
Error: Type 'false' is not assignable to type 'Success'

**In this example: