aimbytes
Back to journalJournal / (009)
Development

15 advancedTypeScript patternsto master

By AimBytesJune 20, 202518 min read

Discover TypeScript 5.x patterns and techniques that will revolutionize your development workflow. From advanced generics to template literal types and conditional type magic that will make your code more robust and developer-friendly.

TypeScript Advanced Patterns

TypeScript 5.x has introduced powerful new features that enable unprecedented type safety and developer experience improvements. These advanced patterns leverage the latest language features to create robust, maintainable, and self-documenting code that scales with your application's complexity.

Template Literal Type Magic

Template literal types are one of TypeScript's most powerful features, enabling compile-time string manipulation and validation. These patterns unlock new possibilities for type-safe APIs and configuration systems.

Advanced Template Literal Patterns
// Pattern 1: Type-safe route parameters
type ExtractRouteParams<T extends string> = 
  T extends `${string}:${infer Param}/${infer Rest}`
    ? { [K in Param]: string } & ExtractRouteParams<Rest>
    : T extends `${string}:${infer Param}`
    ? { [K in Param]: string }
    : {};

type UserRoute = "/users/:userId/posts/:postId";
type Params = ExtractRouteParams<UserRoute>; // { userId: string; postId: string }

// Pattern 2: CSS-in-JS type safety
type CSSProperties = {
  color?: string;
  backgroundColor?: string;
  margin?: `${number}px` | `${number}rem`;
  padding?: `${number}px` | `${number}rem`;
};

type ResponsiveValue<T> = T | {
  [K in `${keyof typeof breakpoints}`]?: T;
};

const breakpoints = { sm: '640px', md: '768px', lg: '1024px' } as const;

// Pattern 3: Event name validation
type EventMap = {
  'user:login': { userId: string; timestamp: Date };
  'user:logout': { userId: string };
  'post:created': { postId: string; authorId: string };
};

type EventName = keyof EventMap;
type EventPayload<T extends EventName> = EventMap[T];

function emit<T extends EventName>(
  event: T, 
  payload: EventPayload<T>
): void {
  // Type-safe event emission
}

Conditional Type Wizardry

Conditional types enable complex type transformations and validations at compile time. These patterns help create flexible APIs that adapt their behavior based on input types.

Type Transformations

  • Recursive type processing
  • Deep readonly transformations
  • Selective property modifications
  • Union type filtering
  • Nested object validation
  • Function signature adaptation

API Design Benefits

  • Self-documenting interfaces
  • Compile-time error prevention
  • Improved developer experience
  • Type-safe configuration
  • Better refactoring support
  • Enhanced IntelliSense
Advanced Conditional Type Patterns
// Pattern 4: Function overload resolution
type OverloadedFunction = {
  (value: string): string;
  (value: number): number;
  (value: boolean): boolean;
};

type ReturnTypeOf<T> = T extends (...args: any[]) => infer R ? R : never;

// Pattern 5: Deep partial with nullable handling
type DeepPartial<T> = {
  [P in keyof T]?: T[P] extends object 
    ? DeepPartial<T[P]> 
    : T[P] | null;
};

// Pattern 6: Branded types for domain modeling
type Brand<T, B> = T & { readonly __brand: B };
type UserId = Brand<string, 'UserId'>;
type Email = Brand<string, 'Email'>;

function createUser(id: UserId, email: Email) {
  // Guaranteed type safety at runtime
}

// Pattern 7: Exhaustive type checking
type Action = 
  | { type: 'LOADING' }
  | { type: 'SUCCESS'; data: any }
  | { type: 'ERROR'; error: string };

function reducer(state: any, action: Action): any {
  switch (action.type) {
    case 'LOADING':
      return { ...state, loading: true };
    case 'SUCCESS':
      return { ...state, loading: false, data: action.data };
    case 'ERROR':
      return { ...state, loading: false, error: action.error };
    default:
      // TypeScript ensures this is never reached
      const _exhaustive: never = action;
      return state;
  }
}

Advanced Generic Patterns

Generic patterns in TypeScript 5.x enable creation of highly reusable and type-safe utilities. These patterns help build flexible abstractions while maintaining complete type safety and excellent developer experience.

Generic Utility Patterns
// Pattern 8: Builder pattern with type accumulation
class QueryBuilder<T = {}> {
  private conditions: T = {} as T;

  where<K extends string, V>(
    key: K, 
    value: V
  ): QueryBuilder<T & Record<K, V>> {
    return new QueryBuilder();
  }

  select<K extends keyof T>(
    ...keys: K[]
  ): QueryBuilder<Pick<T, K>> {
    return new QueryBuilder();
  }

  build(): T {
    return this.conditions;
  }
}

// Usage with full type safety
const query = new QueryBuilder()
  .where('userId', '123')
  .where('status', 'active')
  .select('userId', 'status')
  .build(); // Type: { userId: string; status: string }

// Pattern 9: Recursive data structure validation
type ValidateSchema<T> = {
  [K in keyof T]: T[K] extends object
    ? ValidateSchema<T[K]>
    : T[K] extends string
    ? 'string'
    : T[K] extends number
    ? 'number'
    : 'unknown';
};

// Pattern 10: Function composition with type flow
type Pipe<T extends readonly any[]> = T extends readonly [
  (...args: any[]) => infer A,
  ...infer Rest
] ? Rest extends readonly [(arg: A) => any, ...any[]]
    ? Pipe<Rest>
    : never
  : T extends readonly [(...args: any[]) => infer R]
  ? R
  : never;

declare function pipe<T extends readonly [any, ...any[]]>(
  ...fns: T
): T extends readonly [(...args: infer A) => any, ...any[]]
  ? (...args: A) => Pipe<T>
  : never;

Mapped Type Mastery

Mapped types provide powerful ways to transform existing types. These patterns enable creation of derived types that automatically stay in sync with their source types, reducing maintenance overhead and improving type safety.

Performance and Best Practices

While these advanced patterns are powerful, they must be used judiciously to maintain compilation performance and code readability. Understanding when and how to apply these patterns is crucial for production applications.

Compilation Time

Faster with optimized patterns

Type Safety

Runtime error prevention

Developer Experience

Improved satisfaction

Not sure your app is production-ready?

Send us your link. Within 2 working days you'll get a short screen recording showing 10 security and speed checks on your live app. Free, no call needed.

Written by

AB

AimBytes

Founder-led product engineering studio, Gurugram

AimBytes audits, hardens and scales MVPs and AI-built apps on Next.js, React Native, Supabase and Postgres. Founder-led, with vetted specialists.