Advanced Patterns for Elegant Code
4. Function Composition and Pipelines
Function composition is the art of combining simple functions to build more complex operations. TypeScript's type system makes this particularly powerful and safe.
The Pipe Function
type PipeFunction = { <A, B>(fn1: (arg: A) => B): (arg: A) => B; <A, B, C>(fn1: (arg: A) => B, fn2: (arg: B) => C): (arg: A) => C; <A, B, C, D>(fn1: (arg: A) => B, fn2: (arg: B) => C, fn3: (arg: C) => D): (arg: A) => D; // ... more overloads as needed }; const pipe: PipeFunction = (...fns: Array<(arg: any) => any>) => (value: any) => fns.reduce((acc, fn) => fn(acc), value); // Usage example const processUser = pipe( (user: RawUser) => validateUser(user), (user: ValidUser) => enrichUserData(user), (user: EnrichedUser) => formatUserProfile(user) ); Pipe functions are allow you to chain multiple functions together, where the output of one becomes the input of the next, while preserving type inference across each step.You may already seen them if you already use rxjs pipe function.
Currying for Reusability
const createFilter = <T>(predicate: (item: T) => boolean) => (items: T[]) => items.filter(predicate); const createMapper = <T, U>(transform: (item: T) => U) => (items: T[]) => items.map(transform); // Create reusable functions const filterActive = createFilter((user: User) => user.isActive); const mapToNames = createMapper((user: User) => user.name); const getActiveUserNames = pipe( filterActive, mapToNames ); Here createFilter and createMapper both are higher-order factory functions designed to promote reusability in data processing.
The createFilter and createMapper functions are factory utilities that generate reusable array operations.
createFilter takes a predicate and returns a function that filters arrays based on that condition, while createMapper takes a transform function and returns a function that maps each array item to a new value.
Together, they enable clean, declarative data pipelines—letting you compose custom filtering and transformation logic (e.g., mapToNames(filterActive(users))) with excellent reusability and readability.
5. Type-Safe Error Handling
Moving beyond try-catch blocks to functional error handling patterns.
The Result Pattern
type Result<T, E = Error> = | { success: true; data: T } | { success: false; error: E }; const Ok = <T>(data: T): Result<T, never> => ({ success: true, data }); const Err = <E>(error: E): Result<never, E> => ({ success: false, error }); // Utility functions for Result const map = <T, U, E>( result: Result<T, E>, fn: (value: T) => U ): Result<U, E> => result.success ? Ok(fn(result.data)) : result; const chain = <T, U, E>( result: Result<T, E>, fn: (value: T) => Result<U, E> ): Result<U, E> => result.success ? fn(result.data) : result; // Example usage const parseUser = (json: string): Result<User, string> => { try { const data = JSON.parse(json); return validateUser(data) ? Ok(data) : Err("Invalid user data"); } catch { return Err("Invalid JSON"); } }; const processUserData = (json: string): Result<string, string> => pipe( parseUser, result => map(result, enrichUserData), result => map(result, user => user.displayName) )(json); This code introduces a type-safe Result pattern inspired by functional programming, providing a clean alternative to try/catch error handling.
It wraps success and failure outcomes in explicit types—Ok for success and Err for failure—making it easier to handle errors predictably while keeping code readable and composable.
In detail, the Result type allows functions to return either a success value or an error without throwing exceptions. The helper functions map and chain enable safe transformations and chaining of operations only when the result is successful, skipping computation if an error occurs. In the example, parseUser safely parses and validates user data, while processUserData uses pipe to compose multiple transformations (enrichUserData, user.displayName) in a declarative, error-aware flow — ensuring that every step is type-checked and failure-proof.
Option Pattern for Nullable Values
type Option<T> = T | null | undefined; const Some = <T>(value: T): T => value; const None = null; const mapOption = <T, U>( option: Option<T>, fn: (value: T) => U ): Option<U> => option ? fn(option) : None; const chainOption = <T, U>( option: Option<T>, fn: (value: T) => Option<U> ): Option<U> => option ? fn(option) : None; // Safe navigation without optional chaining const getUserCity = (user: Option<User>): Option<string> => chainOption(user, u => chainOption(u.address, addr => addr.city) ); 6. Advanced Generic Patterns
Conditional Types for Function Overloading
type ApiResponse<T> = T extends string ? { message: T } : T extends number ? { count: T } : T extends object ? { data: T } : never; function createResponse<T>(value: T): ApiResponse<T> { if (typeof value === 'string') { return { message: value } as ApiResponse<T>; } if (typeof value === 'number') { return { count: value } as ApiResponse<T>; } return { data: value } as ApiResponse<T>; } // Type-safe usage const stringResponse = createResponse("Hello"); // { message: string } const numberResponse = createResponse(42); // { count: number } const objectResponse = createResponse({id: 1}); // { data: object } Mapped Types for Transformations
type EventHandlers<T> = { [K in keyof T as `on${Capitalize<string & K>}`]: (value: T[K]) => void; }; type FormData = { email: string; password: string; rememberMe: boolean; }; // Automatically generates: // { // onEmail: (value: string) => void; // onPassword: (value: string) => void; // onRememberMe: (value: boolean) => void; // } type FormHandlers = EventHandlers<FormData>; const createFormHandlers = <T extends Record<string, any>>( onChange: (key: keyof T, value: T[keyof T]) => void ): EventHandlers<T> => { return new Proxy({} as EventHandlers<T>, { get: (target, prop: string) => { if (prop.startsWith('on')) { const key = prop.slice(2).toLowerCase() as keyof T; return (value: T[keyof T]) => onChange(key, value); } return undefined; } }); }; 7. Performance and Optimization Patterns
Memoization with Type Safety
type MemoCache<T extends (...args: any[]) => any> = Map<string, ReturnType<T>>; function memoize<T extends (...args: any[]) => any>( fn: T, keyGenerator?: (...args: Parameters<T>) => string ): T { const cache: MemoCache<T> = new Map(); const defaultKeyGen = (...args: Parameters<T>) => JSON.stringify(args); const keyGen = keyGenerator || defaultKeyGen; return ((...args: Parameters<T>): ReturnType<T> => { const key = keyGen(...args); if (cache.has(key)) { return cache.get(key)!; } const result = fn(...args); cache.set(key, result); return result; }) as T; } // Usage const expensiveCalculation = memoize( (x: number, y: number): number => { console.log(`Calculating ${x} * ${y}`); return x * y; } ); Lazy Evaluation
class Lazy<T> { private _value: T | undefined = undefined; private _computed = false; constructor(private computation: () => T) {} get value(): T { if (!this._computed) { this._value = this.computation(); this._computed = true; } return this._value!; } map<U>(fn: (value: T) => U): Lazy<U> { return new Lazy(() => fn(this.value)); } } const lazy = <T>(computation: () => T): Lazy<T> => new Lazy(computation); // Example usage const expensiveData = lazy(() => { console.log("Computing expensive data..."); return processLargeDataset(); }); // Only computed when accessed const result = expensiveData.map(data => data.summary).value; 8. Functional Programming Utilities
Creating a Functional Toolkit
// Partial application const partial = <T extends any[], U extends any[], R>( fn: (...args: [...T, ...U]) => R, ...partialArgs: T ) => (...remainingArgs: U): R => fn(...partialArgs, ...remainingArgs); // Function composition (right to left) const compose = <T>(...fns: Array<(arg: T) => T>) => (value: T): T => fns.reduceRight((acc, fn) => fn(acc), value); // Debouncing with proper typing const debounce = <T extends (...args: any[]) => any>( fn: T, delay: number ): ((...args: Parameters<T>) => void) => { let timeoutId: NodeJS.Timeout; return (...args: Parameters<T>) => { clearTimeout(timeoutId); timeoutId = setTimeout(() => fn(...args), delay); }; Source:https://dev.to/xtareq/the-art-of-beautiful-functions-in-typescript-part-2-2ibf