-
Utility: Flatten nested types
typescriptThis 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 -
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
typescriptMatching 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