Never underestimate a droid πŸ€–
Menu
Authors profile image

Hey there, I'm JanπŸ‘‹

...and this is my journey through time, code and space. Good luck out thereπŸ––

  • Utility: Flatten nested types

    typescript

    This mapped type is a β€˜noop type’ in the sense that input type === output type. Still, but comes in handy with intersection/composed types when editing code as it flattens the given input type. As an example,

    type Ugly = {id: string;} & {date: Date;}
    // becomes
    type Pretty = {id: string; date: Date;}
    // with
    type Flatten<T> = {
        [K in keyof T]: T[K];
    } & {};
    
    ~ 65 words
  • Nonempty record using proxy

    typescript structures

    This structure guarantees to return a string. It’s super useful for all kinds of functionality like algebraic type specification where a neutral value is required by design.

    const safeRecord = new Proxy(
      {}, {
        get: (handler: Record<PropertyKey, string>, name: PropertyKey) : string => {
          handler[name] ??= ""; return handler[name];
        }
      }
    );
    
    ~ 63 words
  • Array and object type detection

    typescript

    Matching primitive types with typeof is simple. Switching on complex types instead can be a pain - looking at you array and object. Here are two helpers that can be deployed in some conditional type switching logic.

    type DetectArray<T> = number extends keyof T ? true : false;
    // use in type switching
    DetectArray<string[]> // true
    DetectArray<{ [k: number]: unknown }> // true
    
    type DetectStringObj<T> = string extends keyof T ? true : false;
    DetectStringObj<{ [k: string]: unknown }> // true
    DetectStringObj<{ x: string }> // false, because { x: string } is a subtyped object
    
    ~ 89 words