TypeScript – Literal Types


TypeScript – Literal Types


”;


In TypeScript, literal types are subtypes of the primitive data types. The literal types allow you to specify the exact value the variable can contain.

There are three types of the literal types in TypeScript.

  • String literal types

  • Numeric literal types

  • Boolean literal types

Each of them allows you to store the specific value in the variable rather than storing the generalized string, numeric, or boolean value.

Syntax

You can follow the syntax below to use the literal types in TypeScript.

type lit_type = type_1 | type_2 | type_3 | ...

In the above syntax, ”type” is a keyword to create a type alias. The ”lit_type” is the name of the type. The ”type_1”, ”type_2”, and “type_3” are values of type string, Boolean, or number.

String Literal Types

The string literal type allows you to define a set of specific values from which a variable or function parameter should contain any value.

Example

In the code below, we have created the ”Direction” type which contains all 4 directions in string format. The type of the move() function parameter is Direction so it accepts any value from the 4 directions.

If you try to pass any value other than 4 directions as an argument, it throws an error.

// Defining a custom-type Direction
type Direction = "North" | "East" | "South" | "West";

// Defining a function move that takes a single argument of type Direction.
function move(direction: Direction) {
    console.log(`Moving in the direction: ${direction}`);
}
move("North"); 
move("East"); 
// move("Northeast"); 
// Error: Argument of type ''"Northeast"'' is not assignable to parameter of type ''Direction''.

On compiling, it will generate the following JavaScript code.

// Defining a function move that takes a single argument of type Direction.
function move(direction) {
    console.log(`Moving in the direction: ${direction}`);
}
move("North");
move("East");
// move("Northeast"); 
// Error: Argument of type ''"Northeast"'' is not assignable to parameter of type ''Direction''.

The output of the above code is as follows –

Moving in the direction: North
Moving in the direction: East

Numeric Literal Types

Numeric literal types are similar to string literals but allow you to specify exact numeric values as allowed types.

Example

In the code below, the ”SmallPrimes” type contains the small prime numbers till 11 as a value. The type of the ”prime” variable is ”SmallPrimes”. So, it can contain any value from 2, 3, 5, 7, or 11 only.

type SmallPrimes = 2 | 3 | 5 | 7 | 11;
let prime: SmallPrimes;
prime = 7; 
console.log(prime); // 7
// prime = 4; 
// Error: Type ''4'' is not assignable to type ''SmallPrimes''.

On compiling, it will generate the following JavaScript code.

let prime;
prime = 7;
console.log(prime); // 7
// prime = 4; 
// Error: Type ''4'' is not assignable to type ''SmallPrimes''.

The output of the above code is follows –

7

Combined Literal Types

You can combine different types of literals (string, numeric, boolean) using union types to allow a variable to hold a set of specified values.

Example

In the code below, the ”MixedLiterals” type contains the “click”, 404, and true values.

The action variable can contain any singl value from the 3 values of the ”MixedLiterals” type.

// Mixed type literals
type MixedLiterals = "Click" | 404 | true;
let action: MixedLiterals;

action = "Click"; // Valid
console.log(action);

action = 404; // Valid
console.log(action);

action = true; // Valid
console.log(action);
// action = "Other"; 
// Error: Type ''"Other"'' is not assignable to type ''MixedLiterals''.

On compiling, it will generate the following JavaScript code.

let action;
action = "Click"; // Valid
console.log(action);
action = 404; // Valid
console.log(action);
action = true; // Valid
console.log(action);
// action = "Other"; 
// Error: Type ''"Other"'' is not assignable to type ''MixedLiterals''.

The output of the above code is as follows –

Click
404
true

Use Cases for Literal Types

There are multiple use cases of literal types. However, we will look into some real-time use cases of the literal types.

  • Configuration − It is used to define the particular configuration of variables or function parameters that take only specific values.

  • State Management − Type literals can be used for state management.

  • API Response Handling − It is used to handle the API response based on the API response status.

Literal types in TypeScript enhance the type safety of your applications by allowing you to specify exactly what values are acceptable. It also helps developers maintain the code complexity and improve the readability.

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *