Master TypeScript From Scratch

Learn TypeScript step by step with practical examples, interactive coding lessons, and real-world projects.

TypeScript Literal Types

Learn how to restrict variables and function parameters to specific string, number or boolean values using literal types.

Simple Explanation: A literal type allows only a specific value or a defined set of values. It helps prevent invalid values from being used in your application.

1. What are Literal Types?

A literal type restricts a variable to a specific value rather than allowing every value of a general type such as string or number.

For example, a direction variable may allow only "North", "South", "East" or "West". A literal type can enforce this restriction during TypeScript type checking.

Basic Example

let direction: "North" | "South" | "East" | "West";

direction = "North";
console.log(direction);

direction = "East";
console.log(direction);

// This would cause a TypeScript error:
// direction = "Up";

Expected Output

North
East

The variable accepts only the four specified strings. Assigning "Up" would cause a TypeScript type-checking error.

2. Literal Types Workflow Diagram

Understand how literal types define allowed values and help TypeScript identify invalid assignments.

📝
Define Literal Type

Specify the permitted values.

→
📥
Assign Value

Assign a value to the variable or parameter.

→
🔍
Type Checking

TypeScript checks whether the value is allowed.

→
✅
Valid Value

Accepted values can be used in application logic.

Remember: Literal types are checked during development and compilation. They do not automatically validate external data at runtime.

3. String Literal Types

A string literal type accepts only a specific string value. It is useful when a variable must contain one exact value.

Example

let status: "Active";

status = "Active";

console.log(status);

// This would cause a TypeScript error:
// status = "Inactive";

Expected Output

Active

Although the variable is declared using a string literal type, only the exact value "Active" is allowed.

4. String Literal Union Types

You can combine multiple string literals using the union operator (|). The resulting type accepts any of the specified values.

Example: User Roles

type UserRole = "Admin" | "Trainer" | "Student";

function displayRole(role: UserRole): void {
    console.log("Role: " + role);
}

displayRole("Admin");
displayRole("Trainer");
displayRole("Student");

// This would cause a TypeScript error:
// displayRole("Manager");

Expected Output

Role: Admin
Role: Trainer
Role: Student

Allowed Roles Diagram

👑
Admin

An allowed role.

|
👨‍🏫
Trainer

An allowed role.

|
🎓
Student

An allowed role.

The UserRole type permits exactly these three strings. Other values, such as "Manager", are rejected by TypeScript.

5. Numeric Literal Types

Numeric literal types restrict a value to a specific number. They are useful when only particular numeric options are valid.

Example: Application Version

let version: 1 | 2 | 3;

version = 1;
console.log(version);

version = 3;
console.log(version);

// This would cause a TypeScript error:
// version = 4;

Expected Output

1
3

The variable can contain only 1, 2 or 3. The number 4 is not part of the declared union.

6. Boolean Literal Types

Boolean literal types restrict a value to either true or false. These literal types are useful when a particular state must be represented explicitly.

Example

let isReady: true = true;

console.log(isReady);

// This would cause a TypeScript error:
// isReady = false;

Expected Output

true

Here, isReady can only be true. To allow both boolean values, use the general boolean type instead.

7. Literal Types in Functions

Literal types can restrict function parameters. This makes sure the function is called using only the supported options.

Example: Screen Size

type ScreenSize = "small" | "medium" | "large";

function setScreenSize(size: ScreenSize): void {
    console.log("Selected size: " + size);
}

setScreenSize("small");
setScreenSize("medium");
setScreenSize("large");

// This would cause a TypeScript error:
// setScreenSize("extra-large");

Expected Output

Selected size: small
Selected size: medium
Selected size: large

Function Workflow

📥
Receive Argument

The function receives a size value.

→
🔍
Check Type

TypeScript checks the allowed literal values.

→
✅
Execute Function

Supported values can be used by the function.

8. Literal Types and Type Inference

TypeScript uses type inference to determine types from initial values. Variables declared with const can preserve a specific literal type when reassignment is impossible.

Example

const direction = "North";

let currentDirection = "North";

console.log(direction);
console.log(currentDirection);

Expected Output

North
North

Understanding the Types

Declaration Inferred Type Reason
const direction = "North" "North" The const variable cannot be reassigned.
let currentDirection = "North" string The let variable can be reassigned to another string.
Important: Both variables print the same output, but their inferred types differ. Type inference determines what values each variable can accept.

9. Practical Example: Course Enrollment

In a training application, a course enrollment status can be restricted to a fixed set of values so that unexpected status strings are not accepted by normal TypeScript type checking.

Example

type EnrollmentStatus =
    "Registered" | "InProgress" | "Completed";

interface Enrollment {
    studentName: string;
    courseName: string;
    status: EnrollmentStatus;
}

const enrollment1: Enrollment = {
    studentName: "Rahul",
    courseName: "TypeScript",
    status: "InProgress"
};

console.log(enrollment1.studentName);
console.log(enrollment1.courseName);
console.log(enrollment1.status);

Expected Output

Rahul
TypeScript
InProgress

Practical Workflow Diagram

🎓
Define Status

Specify Registered, InProgress and Completed.

→
📋
Create Enrollment

Set the student name and course name.

→
🔍
Check Status

Ensure the status matches an allowed literal.

→
✅
Use Enrollment

Work with the typed enrollment object.

10. Common Mistakes with Literal Types

Mistake Correct Approach
Assigning a string that is not in the literal union. Use one of the explicitly allowed string values.
Assuming a numeric literal union accepts every number. Remember that only the declared numeric values are accepted.
Using a general string when only a few values are valid. Declare a literal union to restrict the permitted strings.
Assuming const and let infer identical types. Understand that const string declarations can infer literal types while let declarations commonly infer string.
Assuming TypeScript validates API input automatically. Use runtime validation for data received from external sources.

11. Advantages of Literal Types

Restricted Values

Allow only predefined values where required.

Type Safety

Help identify invalid assignments and function arguments.

Better Readability

Clearly document allowed states and options in the type definition.

Safer Application Logic

Reduce accidental use of unsupported values during development.

Summary

Literal types restrict values to specific strings, numbers or booleans. Union operators can combine several literal values into one allowed set. Literal types are especially useful for function parameters, application statuses, roles, settings and other predefined choices.

You have completed the Interfaces and Types module. Next, start the Advanced Types module to learn Generics, Generic Constraints, Utility Types and Type Narrowing.