Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
TypeScript Literal Inference Type
Next article icon

TypeScript Literal Types

Last Updated : 21 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Here are the types of literal types in TypeScript:

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"; // Valid assignment // move = "Forward"; // Error: Type '"Forward"' is not assignable to type 'Direction'. 
  • 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.

Output:

move = "Up"; // No error
move = "Forward"; // Compile-time error

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 value     // return 7; // Error: Type '7' is not assignable to type 'DiceRoll'. } 
  • The DiceRoll type allows only the numbers 1 through 6.
  • Returning a number outside this range causes a compile-time error.

Output :

rollDice(); // Returns 4 without error
rollDice(); // Returning 7 causes a compile-time error

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: Type 'false' is not assignable to type 'true'. } 
  • The Success type is strictly true.
  • Returning false would result in a compile-time error.

Output:

operation(); // Returns true without error
operation(); // Returning false causes a compile-time error

Best Practices for Using TypeScript Literal Types

  • Use Literal Types for Exact Values: Define variables with literal types to restrict them to specific, predetermined values, enhancing code predictability.
  • Combine with Union Types: Utilize union types to allow variables to accept a finite set of literal values, improving type safety.
  • Leverage Type Aliases: Create type aliases for complex literal type combinations to simplify code and enhance readability.

Next Article
TypeScript Literal Inference Type

P

pranjalisingh1201
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • TypeScript
  • Geeks Premier League 2023

Similar Reads

  • TypeScript Interfaces Type
    TypeScript Interfaces Type offers an alternative method for defining an object's type, allowing for a distinct naming approach. Syntax:interface InterfaceName { property1: type1; property2?: type2; readonly property3: type3; // ... method1(): returnType1; method2(): returnType2; // ...}Parameters:in
    2 min read
  • TypeScript Literal Inference Type
    TypeScript Literal Inference Type allows you to create type annotations based on actual values, variables, or constants. This enhances type safety and code clarity by specifying that a variable can only hold specific, exact values. It's a way to express the precise values that a variable can take on
    2 min read
  • TypeScript Conditional Types
    In TypeScript, conditional types enable developers to create types that depend on a condition, allowing for more dynamic and flexible type definitions. They follow the syntax T extends U ? X : Y, meaning if type T is assignable to type U, the type resolves to X; otherwise, it resolves to Y.Condition
    4 min read
  • TypeScript Aliases Type
    In TypeScript, a type alias allows you to assign a custom name to an existing type, enhancing code readability and reusability. Provide a shorthand for complex types like unions or objects.Allow naming of primitive types, object types, or functions for clarity.Simplify repetitive type definitions an
    3 min read
  • Data types in TypeScript
    In TypeScript, a data type defines the kind of values a variable can hold, ensuring type safety and enhancing code clarity. Primitive Types: Basic types like number, string, boolean, null, undefined, and symbol.Object Types: Complex structures including arrays, classes, interfaces, and functions.Pri
    3 min read
  • TypeScript any Type
    In TypeScript, any type is a dynamic type that can represent values of any data type. It allows for flexible typing but sacrifices type safety, as it lacks compile-time type checking, making it less recommended in strongly typed TypeScript code. It allows developers to specify types for variables, f
    4 min read
  • TypeScript Generic Types
    TypeScript Generic Types can be used by programmers when they need to create reusable components because they are used to create components that work with various data types and this provides type safety. The reusable components can be classes, functions, and interfaces. TypeScript generics can be u
    2 min read
  • TypeScript Object Types
    TypeScript object types define the structure of objects by specifying property types, ensuring type safety and clarity when passing objects as function parameters. Optional properties, denoted with a ? provide flexibility for objects with varying properties. This approach enhances code robustness by
    3 min read
  • Opaque Types In TypeScript
    In TypeScript Opaque types concept allows for the definition of specialized types such as strings or numbers which are derived from primitive types but do not have the characteristics of the base types, the purpose of this is to prevent specific actions regarding the type in question, or to make thi
    4 min read
  • TypeScript Enums Type
    TypeScript Enums Type is not natively supported by Javascript, but it's a notable feature of the Typescript Programming language. In general, enumerations shortly called "enum" are available in most programming languages to create named consonants. Enums allow us to create a set of named constants,
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences