### Install utility-types Source: https://github.com/piotrwitek/utility-types/blob/master/README.md Install the utility-types package using NPM or YARN. ```bash # NPM npm install utility-types # YARN yarn add utility-types ``` -------------------------------- ### Mapped type examples Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-object-operators.md Demonstrates standard mapped types and mapped types with optional property removal. ```typescript // Standard mapped type type ReadOnly = { readonly [K in keyof T]: T[K]; } // With optional removal type Keys = { [K in keyof T]-?: K }[keyof T]; // -? means: make non-optional (remove the ?) ``` -------------------------------- ### Pick Example (Built-in) Source: https://github.com/piotrwitek/utility-types/blob/master/README.md Selects a subset of properties from an object type based on specified keys. This is a standard TypeScript utility. ```typescript type Props = { name: string; age: number; visible: boolean }; // Expect: { age: number; } type Props = Pick; ``` -------------------------------- ### OptionalKeys Example Source: https://github.com/piotrwitek/utility-types/blob/master/README.md Identifies keys in an object type that are optional. Use this to find properties that may or may not be present. ```typescript import { OptionalKeys } from 'utility-types'; type Props = { req: number; reqUndef: number | undefined; opt?: string; optUndef?: number | undefined; }; // Expect: "opt" | "optUndef" type Keys = OptionalKeys; ``` -------------------------------- ### MutableKeys Example Source: https://github.com/piotrwitek/utility-types/blob/master/README.md Identifies keys in an object type that are mutable (not readonly). Useful for distinguishing between properties that can be reassigned. ```typescript import { MutableKeys } from 'utility-types'; type Props = { readonly foo: string; bar: number }; // Expect: "bar" type Keys = MutableKeys; ``` -------------------------------- ### ReadonlyKeys Example Source: https://github.com/piotrwitek/utility-types/blob/master/README.md Identifies keys in an object type that are readonly. Use this to find properties that cannot be reassigned after initialization. ```typescript import { ReadonlyKeys } from 'utility-types'; type Props = { readonly foo: string; bar: number }; // Expect: "foo" type Keys = ReadonlyKeys; ``` -------------------------------- ### Simplified DeepPartial Recursion Example Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-deep-types.md Illustrates how DeepPartial handles recursion for nested objects. Shows the step-by-step transformation of a deeply nested object type. ```typescript // Simplified DeepPartial recursion type DeepPartial = { [P in keyof T]?: T[P] extends object ? DeepPartial // Recurse into nested objects : T[P] | undefined // Base case: primitive or undefined }; // For { a: { b: { c: string } } } // Step 1: { a?: DeepPartial<{ b: { c: string } }> | undefined } // Step 2: { a?: { b?: DeepPartial<{ c: string }> | undefined } | undefined } // Step 3: { a?: { b?: { c?: string | undefined } | undefined } | undefined } ``` -------------------------------- ### FunctionKeys Example Source: https://github.com/piotrwitek/utility-types/blob/master/README.md Extracts keys from an object type that correspond to function properties. Useful for identifying methods within an object. ```typescript import { FunctionKeys } from 'utility-types'; type MixedProps = { name: string; setName: (name: string) => void }; // Expect: "setName" type Keys = FunctionKeys; ``` -------------------------------- ### Conditional Type Distribution Example Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-union-operators.md Demonstrates how conditional types distribute over union types in TypeScript. Each member of the union is checked independently. ```typescript // This distributes over the union type Dist = T extends string ? 'yes' : 'no'; type Result = Dist<'a' | 'b' | number>; // Equivalent to: ('a' extends string ? 'yes' : 'no') | ('b' extends string ? 'yes' : 'no') | (number extends string ? 'yes' : 'no') // Result: 'yes' | 'yes' | 'no' (simplifies to 'yes' | 'no') ``` -------------------------------- ### RequiredKeys Example Source: https://github.com/piotrwitek/utility-types/blob/master/README.md Extracts keys from an object type that are required. This includes properties that must be present and have a defined value. ```typescript import { RequiredKeys } from 'utility-types'; type Props = { req: number; reqUndef: number | undefined; opt?: string; optUndef?: number | undefined; }; // Expect: "req" | "reqUndef" type Keys = RequiredKeys; ``` -------------------------------- ### Get All Values from Type Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/quick-reference.md Use `ValuesType` to extract all possible values from an object type or a tuple type. ```typescript import { ValuesType } from 'utility-types'; type Config = { host: string; port: number; ssl: boolean }; type ConfigValues = ValuesType; // Result: string | number | boolean type Tuple = [1, 2, 3]; type TupleValues = ValuesType; // Result: 1 | 2 | 3 ``` -------------------------------- ### Get Keys of a Type Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/quick-reference.md Use `$Keys` to extract all keys from an object type `T` as a union of strings. ```typescript import { $Keys } from 'utility-types'; type User = { id: string; name: string }; type Keys = $Keys; // Result: 'id' | 'name' ``` -------------------------------- ### Optional Example Source: https://github.com/piotrwitek/utility-types/blob/master/README.md Makes specified properties of an object type optional. Use this to create variations of an object type with optional fields. ```typescript import { Optional } from 'utility-types'; type Props = { name: string; age: number; visible: boolean; }; // Expect: { name?: string; age?: number; visible?: boolean; } type Props = Optional // Expect: { name: string; age?: number; visible?: boolean; } type Props = Optional; ``` -------------------------------- ### SymmetricDifference Example Source: https://github.com/piotrwitek/utility-types/blob/master/README.md Calculates the symmetric difference between two union types. Use this to find elements present in one type but not both. ```typescript import { SymmetricDifference } from 'utility-types'; // Expect: "1" | "4" type ResultSet = SymmetricDifference<'1' | '2' | '3', '2' | '3' | '4'>; ``` -------------------------------- ### NonFunctionKeys Example Source: https://github.com/piotrwitek/utility-types/blob/master/README.md Extracts keys from an object type that correspond to non-function properties. Use this to isolate data properties. ```typescript import { NonFunctionKeys } from 'utility-types'; type MixedProps = { name: string; setName: (name: string) => void }; // Expect: "name" type Keys = NonFunctionKeys; ``` -------------------------------- ### isPrimitive Type Guard Example Usage Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-aliases-guards.md Demonstrates how to use the isPrimitive type guard to narrow down types in conditional branches. Shows handling of both primitive values and arrays of primitives. ```typescript import { isPrimitive, Primitive } from 'utility-types'; const consumer = (value: Primitive | Primitive[]): string => { if (isPrimitive(value)) { // typeof value === Primitive return String(value) + ' was Primitive'; } // typeof value === Primitive[] const resultArray = value .map(consumer) .map(rootString => '\n\t' + rootString); return resultArray.reduce((comm, newV) => comm + newV, 'this was nested:'); }; console.log(consumer('hello')); // 'hello was Primitive' console.log(consumer([1, 'test', null])); // nested array processing ``` -------------------------------- ### UnionKeys Example Source: https://github.com/piotrwitek/utility-types/blob/master/README.md Retrieves all unique keys present across all object types within a union. Useful for defining a superset of properties for a union. ```typescript import { UnionKeys } from 'utility-types'; type Props = { name: string } | { age: number } | { visible: boolean }; // Expect: "name" | "age" | "visible" type Keys = UnionKeys; ``` -------------------------------- ### Example Usage of isNullish Type Guard Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-aliases-guards.md Demonstrates how to use the isNullish type guard within a conditional to narrow down a parameter type from Nullish | string to string. ```typescript import { isNullish, Nullish } from 'utility-types'; const consumer = (param: Nullish | string): string => { if (isNullish(param)) { // typeof param === Nullish return String(param) + ' was Nullish'; } // typeof param === string return param.toString(); }; console.log(consumer(null)); // 'null was Nullish' console.log(consumer(undefined)); // 'undefined was Nullish' console.log(consumer('hello')); // 'hello' ``` -------------------------------- ### isFalsy Type Guard Example Usage Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-aliases-guards.md Demonstrates using the isFalsy type guard to handle falsy values. Shows how TypeScript narrows the type to Falsy in conditional branches. ```typescript import { isFalsy, Falsy } from 'utility-types'; const consumer = (value: boolean | Falsy): string => { if (isFalsy(value)) { return String(value) + ' was Falsy'; } // typeof value === true (since false is in Falsy) return 'value is true'; }; console.log(consumer(false)); // 'false was Falsy' console.log(consumer(0)); // '0 was Falsy' console.log(consumer('')); // ' was Falsy' (empty string) console.log(consumer(null)); // 'null was Falsy' console.log(consumer(undefined)); // 'undefined was Falsy' console.log(consumer(true)); // 'value is true' ``` -------------------------------- ### $Call Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-special-operators.md Get the return type of a function type Fn. This type is Flow-compatible and works with any callable type. ```APIDOC ## $Call ### Description Get return type of function type (Flow-compatible). Works with any callable type. ### Type Parameters | Parameter | Type | Description | |-----------|------|-------------| | Fn | function type | Function type | ### Returns Return type of the function ### Example Usage ```typescript import { $Call } from 'utility-types'; const add = (x: number, y: number) => ({ sum: x + y }); // Expect: { sum: number } type AddResult = $Call; type Resolver = (value: T) => { resolved: T }; type StringResolver = Resolver; // Expect: { resolved: string } type ResolveResult = $Call; ``` ``` -------------------------------- ### $Diff Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-special-operators.md Get the set difference between two object types. This type is Flow-compatible and removes properties from T that exist in U. ```APIDOC ## $Diff ### Description Get set difference between two object types (Flow-compatible). Removes properties from T that exist in U. ### Type Parameters | Parameter | Type | Description | |-----------|------|-------------| | T | object | Object type (must extend U) | | U | object | Object type with keys to exclude | ### Returns T without properties from U ### Example Usage ```typescript import { $Diff } from 'utility-types'; type User = { id: string; name: string; email: string; password: string }; type PublicUser = { id: string; name: string; email: string }; type HiddenFields = $Diff; // Expect: { password: string } ``` ``` -------------------------------- ### SymmetricDifference Example Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-union-operators.md Computes the symmetric difference (exclusive or) of two union types. Use this to find types present in either union but not both. ```typescript import { SymmetricDifference } from 'utility-types'; // Number ranges type OddNumbers = 1 | 3 | 5 | 7 | 9; type SmallNumbers = 1 | 2 | 3 | 4 | 5; // Expect: 7 | 9 | 2 | 4 // (in OddNumbers but not SmallNumbers) or (in SmallNumbers but not OddNumbers) type Difference = SymmetricDifference; // Feature flags type Feature1 = 'auth' | 'db' | 'cache'; type Feature2 = 'cache' | 'logging' | 'metrics'; // Expect: 'auth' | 'db' | 'logging' | 'metrics' // Features enabled in either config but not both type ExclusiveFeatures = SymmetricDifference; ``` -------------------------------- ### DeepPartial Example Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-deep-types.md Illustrates how to make all properties of a nested object type optional recursively. This is useful for creating types that represent partially filled forms or configurations where many fields can be omitted. ```typescript import { DeepPartial } from 'utility-types'; type User = { id: string; profile: { name: string; email: string; settings: { notifications: boolean; theme: 'light' | 'dark'; }; }; }; type PartialUser = DeepPartial; // Results in: // { // id?: string | undefined; // profile?: { // name?: string | undefined; // email?: string | undefined; // settings?: { // notifications?: boolean | undefined; // theme?: 'light' | 'dark' | undefined; // }; // } | undefined; // } const user: PartialUser = { profile: { name: 'John' // email, settings can be omitted } // id can be omitted }; ``` -------------------------------- ### $PropertyType Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-special-operators.md Get the type of a property at a given key K in an object type T. This type is Flow-compatible. ```APIDOC ## $PropertyType ### Description Get type of property at key K in object T (Flow-compatible). Simple index access to get a property type. ### Type Parameters | Parameter | Type | Description | |-----------|------|-------------| | T | object | Object type | | K | keyof T | Property key | ### Returns Type of property at K ### Example Usage ```typescript import { $PropertyType } from 'utility-types'; type User = { id: string; age: number; active: boolean }; // Expect: string type UserId = $PropertyType; // Expect: number type UserAge = $PropertyType; ``` ``` -------------------------------- ### $Keys Type Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/types.md Gets the union of all property keys in an object type T. This is a Flow-compatible version of keyof T. ```typescript export type $Keys = keyof T; ``` -------------------------------- ### Type Guard Variance Example Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-aliases-guards.md Illustrates the TypeScript type guard contract where functions return a boolean and use the 'is' keyword for type narrowing, enabling automatic type inference in conditional blocks. ```typescript declare let value: unknown; if (isPrimitive(value)) { // TypeScript automatically narrows type to Primitive here const x: Primitive = value; // Valid } if (isFalsy(value)) { // TypeScript automatically narrows type to Falsy here const y: Falsy = value; // Valid } if (isNullish(value)) { // TypeScript automatically narrows type to Nullish here const z: Nullish = value; // Valid } ``` -------------------------------- ### Get Union of Object Keys Source: https://github.com/piotrwitek/utility-types/blob/master/README.md Extracts all keys from an object type and returns them as a union of string literals. Similar to Flow's $Keys. ```typescript import { $Keys } from 'utility-types'; type Props = { name: string; age: number; visible: boolean }; // Expect: "name" | "age" | "visible" type PropsKeys = $Keys; ``` -------------------------------- ### Deprecated getReturnOfExpression Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/overview.md Demonstrates a deprecated function for getting the return type of an expression. The preferred methods are the built-in `ReturnType` or the utility-types `$Call`. ```typescript // DEPRECATED - Don't use function getReturnOfExpression(expression: (...params: any[]) => RT): RT // PREFERRED - Use instead type MyReturnType = ReturnType; type MyReturnType = $Call; ``` -------------------------------- ### Union Distribution Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/overview.md Leverages conditional type distribution over unions to perform operations on each member of a union type. This example shows how to find the intersection of two union types. ```typescript type SetIntersection = A extends B ? A : never; // Distributes over union A, checking each member against B ``` -------------------------------- ### FunctionKeys Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-object-operators.md Get the union type of all keys in an object whose values are functions. It correctly handles optional properties by considering properties with a function type or `undefined` as functions. ```APIDOC ## FunctionKeys ### Description Get union type of all keys whose values are functions. ### Signature ```typescript export type FunctionKeys ``` ### Type Parameters | Parameter | Type | Description | |-----------|------|-------------| | T | object | Object type to inspect | ### Returns Union of keys whose values are functions ### Description Maps over object type T, filtering keys to only those whose property values are functions. Uses `NonUndefined` to handle optional properties correctly - a property with type `(() => void) | undefined` is still considered a function. ### Example Usage ```typescript import { FunctionKeys } from 'utility-types'; type Component = { name: string; render: () => JSX.Element; onClick: (event: Event) => void; onFocus?: () => void; disabled?: boolean; }; // Expect: 'render' | 'onClick' | 'onFocus' type EventHandlers = FunctionKeys; // Practical use: extract handler names type HandlerNames = FunctionKeys; // Can use to create handler maps: Record ``` ``` -------------------------------- ### DeepNonNullable Example Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-deep-types.md Demonstrates how to recursively remove null and undefined from all properties of a nested object type. Use this when you need to ensure that all fields, including those in nested objects and arrays, are guaranteed to have a value. ```typescript import { DeepNonNullable } from 'utility-types'; type ApiResponse = { user?: { id: string | null; name: string | null | undefined; profile?: { bio: string | null; avatar: string | undefined; }; } | null; errors?: (string | null)[]; }; type ValidResponse = DeepNonNullable; // Results in: // { // user: { // id: string; // name: string; // profile: { // bio: string; // avatar: string; // }; // }; // errors: string[]; // } const response: ValidResponse = { user: { id: '123', name: 'John', profile: { bio: 'Developer', avatar: 'https://example.com/avatar.jpg' } }, errors: [] }; ``` -------------------------------- ### Get Property Type of an Object Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-special-operators.md Use $PropertyType to extract the type of a specific property from an object type. This is a Flow-compatible way to get a property's type. ```typescript import { $PropertyType } from 'utility-types'; type User = { id: string; age: number; active: boolean }; // Expect: string type UserId = $PropertyType; // Expect: number type UserAge = $PropertyType; ``` -------------------------------- ### Mutable Example Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-deep-types.md Shows how to remove the readonly modifier from all top-level properties of an object type, making them mutable. Use this when you need to modify properties of an object that was initially defined as readonly. ```typescript import { Mutable } from 'utility-types'; type ImmutableConfig = { readonly version: string; readonly port: number; readonly ssl: boolean; }; type MutableConfig = Mutable; // Results in: // { // version: string; // port: number; // ssl: boolean; // } const config: MutableConfig = { version: '1.0', port: 3000, ssl: true }; config.port = 8000; // Now allowed config.ssl = false; // Now allowed ``` -------------------------------- ### $ReadOnly Type Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/types.md Gets a readonly version of an object type T, using DeepReadonly. This is a Flow-compatible version. ```typescript export type $ReadOnly = DeepReadonly; ``` -------------------------------- ### Extract Keys with Flow Compatibility $Keys Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-special-operators.md Utilize $Keys for Flow compatibility to get a union of all property keys in an object type. This is equivalent to TypeScript's `keyof` operator and is useful for code intended to work across both Flow and TypeScript environments. ```typescript import { $Keys } from 'utility-types'; type Config = { host: string; port: number; ssl: boolean }; // Expect: 'host' | 'port' | 'ssl' type ConfigKeys = $Keys; // Use for type-safe key access function getConfigValue>(key: K): Config[K] { return new Map([ ['host', 'localhost'], ['port', 3000], ['ssl', true] ]).get(key) as any; } ``` -------------------------------- ### Import Pattern for Utility Types Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/overview.md All exports are available directly from the main package. This pattern shows how to import various types and functions. ```typescript import { Primitive, isPrimitive, DeepReadonly, PickByValue, Brand, $Keys, // ... other types } from 'utility-types'; ``` -------------------------------- ### $Values Type Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/types.md Gets the union of all property values in an object type T. This is a Flow-compatible version. ```typescript export type $Values = T[keyof T]; ``` -------------------------------- ### Get Union Keys from Union of Objects Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/types.md Computes the union of all keys present across all object types within a union type U. Useful for working with unions of different object structures. ```typescript export type UnionKeys = keyof UnionToIntersection>; ``` -------------------------------- ### Configuration Management with utility-types Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/advanced-patterns.md Creates configuration objects with readonly and mutable properties, featuring type-safe getters and setters. Imports ReadonlyKeys, MutableKeys, DeepReadonly, and Omit from utility-types. ```typescript import { ReadonlyKeys, MutableKeys, DeepReadonly, Omit } from 'utility-types'; type AppConfig = { readonly version: string; readonly appName: string; debug: boolean; port: number; ssl: { readonly enabled: boolean; cert: string; }; }; type ReadOnlyConfig = ReadonlyKeys; // Result: 'version' | 'appName' | 'ssl' type MutableConfig = MutableKeys; // Result: 'debug' | 'port' type ImmutableSnapshot = DeepReadonly; class ConfigManager { private config: AppConfig; get immutable(): ImmutableSnapshot { return this.config as any; } set>(key: K, value: AppConfig[K]) { this.config[key] = value; } get(key: K): AppConfig[K] { return this.config[key]; } } ``` -------------------------------- ### $ReadOnly Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-special-operators.md Get a deeply readonly version of an object type. This type is Flow-compatible and delegates to `DeepReadonly` for implementation. ```APIDOC ## $ReadOnly ### Description Get deeply readonly version of object type. Flow-compatible type for creating deep readonly types. Delegates to `DeepReadonly` for implementation. ### Type Parameters | Parameter | Type | Description | |-----------|------|-------------| | T | object | Object type | ### Returns T with all properties deeply readonly ### Example Usage ```typescript import { $ReadOnly } from 'utility-types'; type Config = { server: { host: string; port: number }; db: { url: string }; }; type ImmutableConfig = $ReadOnly; // All properties at all levels become readonly ``` ``` -------------------------------- ### MutableKeys / WritableKeys Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-object-operators.md Get the union type of all mutable (non-readonly) keys in an object. `WritableKeys` is an alias for `MutableKeys`. ```APIDOC ## MutableKeys / WritableKeys ### Description Get union type of all mutable (non-readonly) keys. ### Signature ```typescript export type MutableKeys export type WritableKeys = MutableKeys; ``` ### Type Parameters | Parameter | Type | Description | |-----------|------|-------------| | T | object | Object type to inspect | ### Returns Union of mutable property keys ### Description Identifies which properties in object T are mutable (not declared as readonly). Uses type equality checking to determine if removing the `readonly` modifier changes the type. `WritableKeys` is a synonym for `MutableKeys`. ### Example Usage ```typescript import { MutableKeys } from 'utility-types'; type Config = { readonly version: string; readonly name: string; debug: boolean; port: number; }; // Expect: 'debug' | 'port' type EditableFields = MutableKeys; // Extract mutable properties type EditableConfig = Pick; // Result: { debug: boolean; port: number; } // Useful pattern: allow mutation only on certain fields type PartialConfig = Partial>; ``` ``` -------------------------------- ### Get Property Type Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/quick-reference.md Use `$PropertyType` to extract the type of a specific property `P` from type `T`. ```typescript import { $PropertyType } from 'utility-types'; type User = { id: string; age: number }; type IdType = $PropertyType; // Result: string type AgeType = $PropertyType; // Result: number ``` -------------------------------- ### Plugin System with Type Composition Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/advanced-patterns.md Build a plugin system where plugins extend functionality through type composition. Ensure all plugin methods are available on the application instance. ```typescript import { UnionToIntersection } from 'utility-types'; type Plugin = { name: string; methods: Record any>; }; type BasePlugin = { name: 'base'; methods: { log: (msg: string) => void; warn: (msg: string) => void; }; }; type StoragePlugin = { name: 'storage'; methods: { get: (key: string) => any; set: (key: string, value: any) => void; }; }; type CachePlugin = { name: 'cache'; methods: { cache: (key: string, fn: () => any, ttl: number) => any; invalidate: (key: string) => void; }; }; type AllPlugins = BasePlugin | StoragePlugin | CachePlugin; type PluginMethods = UnionToIntersection; class Application { private methods: PluginMethods; async initialize(plugins: Plugin[]) { this.methods = plugins.reduce((acc, plugin) => ({ ...acc, ...plugin.methods, }), {} as PluginMethods); } use(methods: PluginMethods) { this.methods = { ...this.methods, ...methods }; } } // Usage: all plugin methods are available const app = new Application(); // app.methods.log('test'); // app.methods.cache('key', () => {}, 1000); ``` -------------------------------- ### Import All Utility Types Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/quick-reference.md Import all available type utilities from the 'utility-types' library. This is useful for accessing the full range of types in a single import statement. ```typescript import { // Aliases & Guards Primitive, isPrimitive, Falsy, isFalsy, Nullish, isNullish, // Union Operators SetIntersection, SetDifference, SetComplement, SymmetricDifference, NonUndefined, // Object Key Extraction FunctionKeys, NonFunctionKeys, MutableKeys, WritableKeys, ReadonlyKeys, RequiredKeys, OptionalKeys, UnionKeys, // Object Selection & Transformation PickByValue, PickByValueExact, OmitByValue, OmitByValueExact, Intersection, Diff, Subtract, Overwrite, Assign, Optional, Required, ValuesType, // Deep Transformations DeepReadonly, DeepRequired, DeepPartial, DeepNonNullable, Mutable, Writable, // Special Operators Unionize, PromiseType, Brand, UnionToIntersection, Exact, // Flow Compatibility $Keys, $Values, $ReadOnly, $Diff, $PropertyType, $ElementType, $Call, $Shape, $NonMaybeType, Class, mixed, } from 'utility-types'; ``` -------------------------------- ### Get Return Type of Function Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/quick-reference.md Use `$Call` to infer the return type of a function type `T`. ```typescript import { $Call } from 'utility-types'; const getUser = () => ({ id: '1', name: 'John' }); type User = $Call; // Result: { id: string; name: string } ``` -------------------------------- ### Get Values from a Const Object Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/quick-reference.md Use `$Values` to extract all values from a `const` object type `T` as a union of types. ```typescript import { $Values } from 'utility-types'; const STATUS = { IDLE: 'idle', LOADING: 'loading', } as const; type Status = $Values; // Result: 'idle' | 'loading' ``` -------------------------------- ### Merging Defaults with Partial Input Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-deep-types.md Illustrates merging default values with user input that is a DeepPartial type. This pattern is common for applying configurations or defaults. ```typescript import { DeepPartial, DeepRequired } from 'utility-types'; type Defaults = { /* ... */ }; type UserInput = DeepPartial; function applyDefaults( defaults: T, input: DeepPartial ): T { // Merge defaults with partial input } ``` -------------------------------- ### $PropertyType Type Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/types.md Gets the type of a specific property K within an object type T. This is a Flow-compatible version. ```typescript export type $PropertyType = T[K]; ``` -------------------------------- ### Fluent Builder Pattern with Strict Type Checking Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/advanced-patterns.md Implement a fluent builder API where type safety is enforced at each step. The `build()` method is only available after all required configuration fields are set. ```typescript import { Optional, Required } from 'utility-types'; type QueryConfig = { select?: string[]; where?: Record; orderBy?: string; limit?: number; }; class QueryBuilder = {}> { private config: T; constructor(config: T = {} as T) { this.config = config; } select>( fields: string[] ): QueryBuilder { return new QueryBuilder({ ...this.config, select: fields } as any); } where>( conditions: Record ): QueryBuilder { return new QueryBuilder({ ...this.config, where: conditions } as any); } limit>( count: number ): QueryBuilder { return new QueryBuilder({ ...this.config, limit: count } as any); } build(this: QueryBuilder>): Required { return this.config as Required; } } // Usage: build() is only available after all required fields are set const query = new QueryBuilder() .select(['id', 'name']) .where({ active: true }) .limit(10) .build(); ``` -------------------------------- ### Brand Safe Currency Handling Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/overview.md Employs the `Brand` utility to create distinct nominal types for different currencies (e.g., USD, EUR) from a base numeric type. This prevents type confusion and ensures that currency values are used correctly. ```typescript import { Brand } from 'utility-types'; type USD = Brand; type EUR = Brand; function convertToEur(amount: USD): EUR { /* ... */ } // Type system prevents USD/EUR confusion ``` -------------------------------- ### Get Union of Object Values Source: https://github.com/piotrwitek/utility-types/blob/master/README.md Extracts all values from an object type and returns them as a union of their types. Similar to Flow's $Values. ```typescript import { $Values } from 'utility-types'; type Props = { name: string; age: number; visible: boolean }; // Expect: string | number | boolean type PropsValues = $Values; ``` -------------------------------- ### Implement Type-Safe State Machine Transitions Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/advanced-patterns.md Use `Unionize` to create a type-safe state machine where only valid transitions between states are allowed, preventing runtime errors and improving code maintainability. ```typescript import { Unionize } from 'utility-types'; type StateMachine = { IDLE: { LOAD: { data: any } | { error: Error } }; LOADING: { SUCCESS: any; ERROR: Error }; SUCCESS: { RESET: void }; ERROR: { RESET: void; RETRY: void }; }; type States = keyof StateMachine; type ValidTransition = Unionize< StateMachine[S] >; class Machine { constructor(private state: S) {} transition( newState: T, ...args: ValidTransition extends { [K in T]: infer P } ? [P] : never ) { // Implementation } } // Usage with type safety const machine = new Machine('IDLE' as const); // Valid transitions machine.transition('LOADING'); machine.transition('IDLE'); // Invalid transitions would be caught by TypeScript // machine.transition('SUCCESS'); // ERROR: not valid from IDLE ``` -------------------------------- ### NonFunctionKeys Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-object-operators.md Get the union type of all keys in an object whose values are not functions. This is the complement of `FunctionKeys` and is useful for extracting data properties. ```APIDOC ## NonFunctionKeys ### Description Get union type of all keys whose values are not functions. ### Signature ```typescript export type NonFunctionKeys ``` ### Type Parameters | Parameter | Type | Description | |-----------|------|-------------| | T | object | Object type to inspect | ### Returns Union of keys whose values are not functions ### Description Maps over object type T, filtering keys to only those whose property values are not functions. Complement of `FunctionKeys`. Useful for extracting data properties distinct from methods. ### Example Usage ```typescript import { NonFunctionKeys } from 'utility-types'; type MixedProps = { name: string; age: number; render: () => JSX.Element; onClick: (event: Event) => void; }; // Expect: 'name' | 'age' type DataKeys = NonFunctionKeys; // Extract only data properties type DataProps = Pick; // Result: { name: string; age: number; } ``` ``` -------------------------------- ### Get Element Type of Tuple Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/quick-reference.md Use `$ElementType` to extract the type of an element at a specific index `N` from a tuple type `T`. ```typescript import { $ElementType } from 'utility-types'; type Tuple = [string, number, boolean]; type First = $ElementType; // Result: string type Second = $ElementType; // Result: number ``` -------------------------------- ### Create Branded Types for Domain IDs Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/advanced-patterns.md Use `Brand` to create distinct types for domain entities like UserID, PostID, and MoneyAmount, preventing accidental mixing and enhancing type safety. Helper functions are provided to create these branded types. ```typescript import { Brand } from 'utility-types'; // Domain IDs type UserId = Brand; type PostId = Brand; type CommentId = Brand; // Domain value objects type MoneyAmount = Brand; type PercentageValue = Brand; // Helper functions to create branded types const createUserId = (id: string): UserId => id as UserId; const createPostId = (id: string): PostId => id as PostId; const createMoney = (amount: number): MoneyAmount => amount as MoneyAmount; // API functions that enforce type safety function getUser(id: UserId): Promise { return fetch(`/users/${id}`).then(r => r.json()); } function getPost(id: PostId): Promise { return fetch(`/posts/${id}`).then(r => r.json()); } function calculateTax(amount: MoneyAmount): MoneyAmount { return (amount * 0.1) as MoneyAmount; } // Type-safe usage const userId = createUserId('user123'); const postId = createPostId('post456'); getUser(userId); // ✓ OK // getUser(postId); // ✗ ERROR: PostId not assignable to UserId getPost(postId); // ✓ OK const price = createMoney(100); const tax = calculateTax(price); // const taxPercentage: PercentageValue = tax; // ✗ ERROR: MoneyAmount not assignable to PercentageValue ``` -------------------------------- ### Type-Safe API Client with utility-types Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/advanced-patterns.md Ensures API calls return strictly typed responses based on endpoint definitions. Imports $ElementType and PromiseType from utility-types. ```typescript import { $ElementType, PromiseType } from 'utility-types'; // Define all API endpoints const API = { getUser: (id: string): Promise<{ id: string; name: string; email: string }> => fetch(`/users/${id}`).then(r => r.json()), getPost: (id: string): Promise<{ id: string; title: string; content: string }> => fetch(`/posts/${id}`).then(r => r.json()), listUsers: (): Promise<{ id: string; name: string }[]> => fetch('/users').then(r => r.json()), }; // Endpoint type type Endpoint = keyof typeof API; // Get return type of any endpoint type GetResponse = PromiseType>; // Usage with type safety async function handleUser() { const user = await API.getUser('123'); type User = GetResponse<'getUser'>; // User = { id: string; name: string; email: string } } ``` -------------------------------- ### Create Brand Safe Types Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/quick-reference.md Use the `Brand` utility to create distinct types from existing ones, preventing accidental assignment between similar types. This enhances type safety by ensuring specific contexts for values. ```typescript import { Brand } from 'utility-types'; type UserId = Brand; type PostId = Brand; const userId = '123' as UserId; const postId = '456' as PostId; function getUser(id: UserId) { /* ... */ } getUser(userId); // ✓ OK getUser(postId); // ✗ ERROR: PostId not assignable to UserId ``` -------------------------------- ### Pick Properties by Exact Value Type Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/types.md Creates a new object type by picking properties from T whose values exactly match ValueType. This is stricter than PickByValue, requiring an exact type match. ```typescript export type PickByValueExact = Pick< T, { [Key in keyof T]-?: [ValueType] extends [T[Key]] ? [T[Key]] extends [ValueType] ? Key : never : never; }[keyof T] >; ``` -------------------------------- ### Get Element Type Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/types.md Extracts the type of an element at a specific index or key from an array-like object or tuple. Useful for accessing nested types. ```typescript export type $ElementType< T extends { [P in K & any]: any }, K extends keyof T | number > = T[K]; ``` -------------------------------- ### Type for Class Constructor Source: https://github.com/piotrwitek/utility-types/blob/master/README.md Represents the type of a class constructor. This utility is used to type constructor parameters, allowing for dependency injection of class instances. ```typescript import { Class } from 'utility-types'; function makeStore(storeClass: Class): Store { return new storeClass(); } ``` -------------------------------- ### Get Required Keys of an Object Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/types.md Determines the union type of all keys in an object T that are required (non-optional). Useful for ensuring all necessary properties are present. ```typescript export type RequiredKeys = { [K in keyof T]-?: {} extends Pick ? never : K; }[keyof T]; ``` -------------------------------- ### $ElementType Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-special-operators.md Get the type of an element at a given index K in a type T. This type is Flow-compatible and works with arrays, objects, and tuples. ```APIDOC ## $ElementType ### Description Get type of element at index K in T (Flow-compatible). Works with objects, arrays, and tuples using either string keys or numeric indices. ### Type Parameters | Parameter | Type | Description | |-----------|------|-------------| | T | array-like \| object | Type to index | | K | keyof T \| number | Index or key | ### Returns Type at index K ### Example Usage ```typescript import { $ElementType } from 'utility-types'; type Tuple = [string, number, boolean]; // Expect: string type First = $ElementType; // Expect: number type Second = $ElementType; type Obj = { key: string }; // Expect: string type ObjValue = $ElementType; ``` ``` -------------------------------- ### Using Type Guard Functions Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/quick-reference.md Utilize type guard functions like `isPrimitive`, `isFalsy`, and `isNullish` to narrow down types within conditional blocks. These functions help TypeScript infer more specific types based on runtime checks. ```typescript import { isPrimitive, isFalsy, isNullish } from 'utility-types'; // Type narrowing if (isPrimitive(value)) { // value is now Primitive } if (isFalsy(value)) { // value is now Falsy } if (isNullish(value)) { // value is now Nullish } ``` -------------------------------- ### Create a Partial Shape of a Type Source: https://github.com/piotrwitek/utility-types/blob/master/README.md Creates a new type by copying the shape of a given type, but making all its properties optional. This is equivalent to TypeScript's Partial utility type. ```typescript import { $Shape } from 'utility-types'; type Props = { name: string; age: number; visible: boolean }; // Expect: Partial type PartialProps = $Shape; ``` -------------------------------- ### Nominal Typing via Branding Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/overview.md Creates nominal types within TypeScript's structural type system by adding a unique, non-existent property (`__brand`). This prevents accidental assignment between types that are structurally similar but semantically distinct. ```typescript type Brand = T & { __brand: U }; // __brand property exists only at type level ``` -------------------------------- ### Deep Readonly for Immutable Config Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/quick-reference.md Use `DeepReadonly` to create a deeply immutable version of a configuration object, preventing accidental modifications. ```typescript import { DeepReadonly } from 'utility-types'; type Config = { server: { host: string; port: number; ssl: { enabled: boolean; cert: string; }; }; }; type ImmutableConfig = DeepReadonly; // All properties are readonly at all levels const config: ImmutableConfig = { /* ... */ }; // config.server.ssl.enabled = false; // ERROR: readonly ``` -------------------------------- ### Get Optional Keys of an Object Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/types.md Identifies the union type of all optional keys within an object type T. Useful for understanding which properties can be omitted. ```typescript export type OptionalKeys = { [K in keyof T]-?: {} extends Pick ? K : never; }[keyof T]; ``` -------------------------------- ### Extract All Keys from Union of Object Types Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-object-operators.md Extracts all possible property keys from a union of object types. Works by converting the union to an intersection and then making it partial. Returns the union of all keys that appear in any object of U. ```typescript import { UnionKeys } from 'utility-types'; type Dog = { name: string; breed: string; }; type Cat = { name: string; color: string; }; type Bird = { species: string; canFly: boolean; }; type Pet = Dog | Cat | Bird; // Expect: 'name' | 'breed' | 'color' | 'species' | 'canFly' type AllPetKeys = UnionKeys; // Practical: find common serialization keys type Shape = { x: number; y: number } | { radius: number }; type AllShapeKeys = UnionKeys; // Result: 'x' | 'y' | 'radius' ``` -------------------------------- ### SetComplement: Calculating Set Complement Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/api-reference-union-operators.md A semantic wrapper around `SetDifference` to compute the complement of a subset within a larger set. Ensure the second type parameter is a subset of the first for correct results. ```typescript import { SetComplement } from 'utility-types'; // State machine states type AllStates = 'initial' | 'active' | 'paused' | 'stopped'; // Expect: 'initial' | 'active' | 'paused' type RunningStates = SetComplement; // Permission levels type AllPermissions = 'read' | 'write' | 'delete' | 'admin'; // Expect: 'read' | 'write' type SafePermissions = SetComplement; ``` -------------------------------- ### Get Function Return Type Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/types.md Extracts the return type of a given function type. This is useful when you need to work with the output type of a function without calling it. ```typescript export type $Call any> = Fn extends ( arg: any ) => infer RT ? RT : never; ``` -------------------------------- ### TypeScript ValuesType Type Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/types.md Extracts the union of all values from an object, array, tuple, or array-like type T. Useful for getting all possible values within a collection. ```typescript export type ValuesType< T extends ReadonlyArray | ArrayLike | Record > = T extends ReadonlyArray ? T[number] : T extends ArrayLike ? T[number] : T extends object ? T[keyof T] : never; ``` -------------------------------- ### Get Readonly Keys of an Object Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/types.md Extracts a union type of all readonly keys from a given object type T. Useful for enforcing immutability on specific properties. ```typescript export type ReadonlyKeys = { [P in keyof T]-?: IfEquals< { [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, never, P >; }[keyof T]; ``` -------------------------------- ### Exact Type Source: https://github.com/piotrwitek/utility-types/blob/master/_autodocs/types.md Creates a branded object type for exact type matching. It ensures that an object matches the type exactly, without allowing extra properties. ```typescript export type Exact = A & { __brand: keyof A }; ```