VOOZH about

URL: https://www.geeksforgeeks.org/typescript/typescript-literal-types/

⇱ TypeScript Literal Types - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

TypeScript Literal Types

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.

  • Allow variables to have specific, exact values.
  • Enhance code reliability by restricting permissible 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.

Output:

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

In this example:

  • The Direction type can only be one of the specified string literals: "Up", "Down", "Left", or "Right".
  • Assigning any value outside this set results in a compile-time error.

2. Numeric Literal Types

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

Output :

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

In this example:

  • The DiceRoll type allows only the numbers 1 through 6.
  • Returning a number outside this range causes a compile-time error.

3. Boolean Literal Types

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

Output:

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

In this example:

  • The Success type is strictly true.
  • Returning false would result in a compile-time error.
Comment
Article Tags:

Explore