Open In App

TypeScript Literal Types

Last Updated : 03 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

TypeScript Literal Types allow us to specify exact values as types of variables or types of return types of a function other than primitive data types this language contains. Literal Types define types of exact values in contrast to primitive types such as `number` which allows us to use a range of possible values. Therefore, these Literal Types only accept specific predefined values. This feature makes a variable, parameter, properties have extremely precise values of the type.

Syntax:

let x : "hello";   // x represents as type "hello".
type myMonthLiteral = "April" | "May" | "June";   //myMonthLiteral can represent one of these values : "April" or "May" or "June".

Where:

  • (`|`) pipe operator is the union sign.
  • x is the variable name
  • type‘ is a keyword used to declare types and myMonthLiteral is the variable name.

Example 1: In this example, Here mycolor is of type “red” and myLuckyNumber is of type`89. If try assigning other values to these specific type variables, they will throw an error.

Javascript




// declare variables with specific types.
let myColor: "red";
let myLuckyNumber: 89;
  
// Assign Variables
myColor = "red";
myLuckyNumber = 89;
  
console.log(`My color is ${myColor}`);
console.log(`My Lucky Number is ${myLuckyNumber}`);
  
// If try assigning other values to these
// specific type variables, they will throw an error.
// myColor = "blue";   // error TS2322: Type
//  '"blue"' is not assignable to type '"red"'.
// myLuckyNumber = 98;  // error TS2322:
// Type '98' is not assignable to type '89'.


Output:

My color is red
My Lucky Number is 89

Example 2: Here printLICPlanStatus function has a parameter status which can be of type “active” or “inactive“.

Javascript




function printLICPlanStatus(status: "active" | "inactive"): void {
    console.log(`Status: ${status}`);
}
  
printLICPlanStatus("active"); 
// Valid - Status can be specifically of
// type "active" or "inactive".
// printLICPlanStatus("disabled");
 // Invalid - error TS2345: Argument of type '"disabled"' 
 // is not assignable to parameter of type '"active" | "inactive"'.


Output :

Status: active

Conclusion: TypeScript Literal Types are valuable tools to catch errors at compile time and build more robust and maintainable applications. They help in creating precise type checking in complex data structures. This features enables users to create their own types in the application to make code safer and strongly typed.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads