Exclude, Extract, and NonNullable Utility Types

1. Welcome and Icebreaker:

  • If you could exclude, extract, or make non-nullable any part of your daily routine, what would it be?

2. Outline the Session:

  • We’ll learn about the built-in utility types Exclude, Extract, and NonNullable in TypeScript.
  • Learning Outcomes: Understand how to use these types to manipulate union types and remove null/undefined.
  • Let’s clean up our types!

3. Concept Explanation:

  • Exclude<T, U>: Excludes from T those types that are assignable to U.
  • Extract<T, U>: Extracts from T those types that are assignable to U.
  • NonNullable<T>: Excludes null and undefined from T.
  • These are useful for refining and filtering types.
  • Syntax:
    type A = Exclude<'a' | 'b' | 'c', 'a'>; // 'b' | 'c'
    type B = Extract<string | number | (() => void), Function>; // () => void
    type C = NonNullable<string | null | undefined>; // string
    

4. Live Coding Demonstration:

type Status = 'pending' | 'active' | 'archived';
type ActiveStatus = Exclude<Status, 'archived'>;
type OnlyArchived = Extract<Status, 'archived'>;
type Name = string | null | undefined;
type NonNullName = NonNullable<Name>;

const status: ActiveStatus = 'active';
// const archived: ActiveStatus = 'archived'; // Error

5. Tasks:

  • Short Exercise:
    1. Create a union type and use Exclude to remove one value.
    2. Use Extract to get only certain values from a union.
    3. Use NonNullable to remove null and undefined from a type.