0Pricing
TypeScript Academy · Lesson

Literal Types

Use exact values as types in TypeScript.

1

Literal Types

Welcome to the next lesson! In this lesson, you’ll learn about literal types, a TypeScript feature that allows you to define exact, specific values for variables. This makes your code more predictable and type-safe. Let’s dive in!

Literal Types  — illustration 1

2

What Are Literal Types?

Literal types in TypeScript allow a variable to hold a specific value, rather than just a general type like string or number. For example, you can restrict a variable to only hold the value "yes" or "no".

Example:

Task: Declare a variable with a literal type and assign valid and invalid values to it.

let answer: "yes" | "no";
answer = "yes"; 
// Valid
// answer = "maybe"; 
// Error: Type '"maybe"' is not assignable to type '"yes" | "no"'.

All lessons in this course

  1. Arrays and Tuples
  2. Union and Intersection Types
  3. Enums
  4. Literal Types
← Back to TypeScript Academy