TypeScript Literal Types
Last Updated :
03 Nov, 2023
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
let myColor: "red" ;
let myLuckyNumber: 89;
myColor = "red" ;
myLuckyNumber = 89;
console.log(`My color is ${myColor}`);
console.log(`My Lucky Number is ${myLuckyNumber}`);
|
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" );
|
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.
Share your thoughts in the comments
Please Login to comment...