JavaScript · Advanced level

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

Narrowing and Generics

Narrow union types safely in code and write reusable functions and types with generics.

In this lesson you will

  • Narrow types with typeof, in, equality and discriminated unions
  • Write generic functions and types

Key concepts

type narrowingdiscriminated uniongeneric function <T>unknown vs any

The lesson

TypeScript narrows a union when you check it: inside if (typeof value === "string") it knows value is a string. With a discriminated union, switching on state.status gives access to the right properties in each case.

Generics make reusable typed code: function last<T>(items: T[]): T | undefined. A generic Result<T> type can describe either a value of T or an error, keeping types precise everywhere it is used.

Avoid any, which switches type checking off. Use unknown for data whose type you do not know yet — such as JSON from a server — and narrow or validate it before use.

Step by step

  1. Render the view state with a switch on status.
  2. Write a generic last<T> function.
  3. Type JSON from fetch as unknown.
  4. Write a type guard that validates a Visit.

Practice activity

Write a typed, validated API client that returns Result<Visit[]> and never uses any.

Expected result: The client compiles in strict mode with no any, and invalid server data is rejected by the type guard.

Check your understanding

  1. Why prefer unknown over any for API data?

    Show answer

    unknown forces you to check the data before using it; any disables checking.

  2. What is a discriminated union?

    Show answer

    A union of object types sharing a property, such as status, whose value identifies each case.

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.