String, Number, and Combined Literals - Textnotes

String, Number, and Combined Literals


Learn how to use literal types in TypeScript to define exact values. This module explains string literal types, number literal types, and combining literal types with practical examples.

1. String Literal Types

String literal types allow a variable to hold only a specific set of string values.

Basic Example


type Direction = "Up" | "Down" | "Left" | "Right";

let move: Direction;

move = "Up"; // Valid
move = "Down"; // Valid
// move = "Forward"; // Error

String literal types are useful for defining controlled values, such as configuration options or states.

2. Number Literal Types

Number literal types restrict a variable to specific numeric values.

Example


type StatusCode = 200 | 404 | 500;

let code: StatusCode;

code = 200; // Valid
code = 404; // Valid
// code = 201; // Error

Number literal types are commonly used for API status codes or fixed numeric options.

3. Combining Literal Types

You can combine string and number literal types or union them with other types for greater flexibility.

Example


type RequestStatus = "pending" | "success" | "failed" | 0 | 1;

let status: RequestStatus;

status = "pending"; // Valid
status = 1; // Valid
// status = 2; // Error

With Functions


function updateStatus(status: "active" | "inactive"): void {
console.log(`Status updated to ${status}`);
}

updateStatus("active"); // Valid
// updateStatus("pending"); // Error

Combining literal types ensures strict control over allowed values, reducing runtime errors.

Conclusion

Literal types in TypeScript provide precise control over variable values. String and number literals, combined with union types, enforce strict typing and make applications more predictable and safer for real-world development.