Skip to content
Alexander Opalic
Alexander Opalic

TypeScript Type Extraction Patterns

Learn powerful TypeScript patterns for extracting and transforming nested types from complex interfaces.

Extract Nested Types from Complex Interfaces

interface GetTodoQuery {
  
GetTodoQuery.todo?: {
    id: number;
    title: string;
    completed: boolean;
    tags?: Array<{
        id: number;
        name: string;
        color: string;
    }> | null;
    collaborators?: Array<{
        userId: number;
        role: "VIEWER" | "EDITOR";
        joinedAt: string;
    }> | null;
} | undefined
todo
?: {
id: numberid: number; title: stringtitle: string; completed: booleancompleted: boolean;
tags?: {
    id: number;
    name: string;
    color: string;
}[] | null | undefined
tags
?: interface Array<T>Array<{
id: numberid: number; name: stringname: string; color: stringcolor: string; }> | null;
collaborators?: {
    userId: number;
    role: "VIEWER" | "EDITOR";
    joinedAt: string;
}[] | null | undefined
collaborators
?: interface Array<T>Array<{
userId: numberuserId: number; role: "VIEWER" | "EDITOR"role: 'VIEWER' | 'EDITOR'; joinedAt: stringjoinedAt: string; }> | null; } } // Extract nested types safely type
type TodoTags = {
    id: number;
    name: string;
    color: string;
}[]
TodoTags
= type NonNullable<T> = T & {}
Exclude null and undefined from T
NonNullable
<type NonNullable<T> = T & {}
Exclude null and undefined from T
NonNullable
<GetTodoQuery['todo']>['tags']>;
type
type TodoTag = {
    id: number;
    name: string;
    color: string;
}
TodoTag
=
type TodoTags = {
    id: number;
    name: string;
    color: string;
}[]
TodoTags
[number];

Key Patterns

  1. Handle optional properties: NonNullable<T> removes undefined and null
  2. Access nested types: Chain properties using ['prop']
  3. Extract array item type: Use [number] index

Perfect for working with GraphQL queries and complex API responses where you need to extract specific nested types safely.

#typescript #types #patterns