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: number
id: number;
title: string
title: string;
completed: boolean
completed: boolean;
tags?: {
id: number;
name: string;
color: string;
}[] | null | undefined
tags?: interface Array<T>
Array<{
id: number
id: number;
name: string
name: string;
color: string
color: string;
}> | null;
collaborators?: {
userId: number;
role: "VIEWER" | "EDITOR";
joinedAt: string;
}[] | null | undefined
collaborators?: interface Array<T>
Array<{
userId: number
userId: number;
role: "VIEWER" | "EDITOR"
role: 'VIEWER' | 'EDITOR';
joinedAt: string
joinedAt: 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 TNonNullable<type NonNullable<T> = T & {}
Exclude null and undefined from TNonNullable<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
- Handle optional properties:
NonNullable<T>
removesundefined
andnull
- Access nested types: Chain properties using
['prop']
- 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