JavaScript · Advanced level

Advanced level · Module 4: TypeScript Essentials · Lesson 2 of 4

Types for Data: Interfaces, Unions and Literals

Describe data shapes with interfaces and type aliases, and model choices with union and literal types.

In this lesson you will

  • Write interfaces and type aliases for application data
  • Use union and literal types for states and options

Key concepts

interface and type aliasoptional propertiesunion typesliteral types

The lesson

interface Visit { id: string; householdId: string; date: string; notes?: string } describes the shape of a visit; the ? marks an optional property. Type aliases (type VisitStatus = …) name any type, including unions.

Union types say a value can be one of several types: string | number. Literal types restrict values to specific ones: type SyncState = "pending" | "synced" | "failed". Misspelling a state then becomes a compile error.

Model a view's state as a union of objects — { status: "loading" } | { status: "error"; message: string } | { status: "ready"; visits: Visit[] } — so impossible combinations cannot be represented.

Step by step

  1. Write interfaces for Visit and Household.
  2. Type the sync state with a literal union.
  3. Model the list view state as a union of objects.
  4. Introduce a misspelt state and read the error.

Practice activity

Type all data structures of the visit tracker.

Expected result: Every data structure has a type, and invalid states produce compile errors.

Check your understanding

  1. What does notes?: string mean?

    Show answer

    notes is optional; when present it is a string.

  2. What is a literal type?

    Show answer

    A type allowing only specific values, such as "pending" | "synced".

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.