Include<T, U>

A more inclusive complement to TypeScript's Exclude helper type - only include the parts of a union type that are assignable to another type.

typescriptjavascript
export type Include<T, U> = T extends U ? T : never
export {}

Usage

typescriptjavascript
type OpenAIMessage =
  | {
      role: 'user'
      content: string
    }
  | {
      role: 'ai'
      content?: string
      function_call?: {
        name: string
        arguments: string
      }
    }
 
/**
 * This type is now only the user part of the message.
 */
type UserMessage = Include<OpenAIMessage, { role: 'user' }>
 
Created 07/09/23
Found a mistake, or want to suggest an improvement? Source on GitHub here
and see edit history here