More Utility Types

More Utilities
πŸ‘¨β€πŸ’Ό Let's explore more utility types for objects and union types.
type Shelf = Record<string, number>
type LockedBook = Readonly<{ title: string; pages: number }>
type BookPreview = Omit<{ id: string; title: string; summary: string }, 'id'>
type FullBook = Required<{ title?: string; author?: string }>

type Status = 'draft' | 'published' | null
type PublishedOnly = Exclude<Status, 'draft' | null>

Object Utilities

  • Record<K, V> - Create object with keys K and values V
  • Readonly<T> - Make all properties readonly
  • Omit<T, K> - Remove properties K from T
  • Required<T> - Make all properties required

Union Utilities

  • Exclude<T, U> - Remove types assignable to U from T
  • Extract<T, U> - Keep only types assignable to U in T
  • NonNullable<T> - Remove null and undefined from T
🐨 Open
index.ts
and:
  1. Create Config as string keys β†’ number values, then a config value { timeout: 5000, retries: 3 }
  2. Create ReadonlyUser and a readonlyUser fixture { id: '1', name: 'Alice', email: 'a@b.com' }
  3. Create UserWithoutId and a newUser fixture { name: 'Bob', email: 'b@b.com' }
  4. Create RequiredUser and a fullUser fixture that includes required bio: 'Hello!' and website: 'https://alice.dev'
  5. For Status = 'pending' | 'active' | 'inactive' | 'deleted' | null | undefined:
    • ActiveStatus β€” Status values that remain after removing deleted and nullish entries
    • ValidStatus β€” removes null and undefined
    • StringStatus β€” keeps only the string variants
  6. Create fixtures status = 'active' (typed as ValidStatus) and activeStatus = 'pending' (typed as ActiveStatus)
  7. Export config, readonlyUser, newUser, fullUser, status, and activeStatus

Please set the playground first

Loading "More Utility Types"
Loading "More Utility Types"