### Basic Setup and Enum Definition for ts-enum-util Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Demonstrates how to import the `$enum` helper function from `ts-enum-util` and defines a sample string enum `RGB` for subsequent examples. It highlights the library's support for various enum types, including basic numeric, string, and mixed enums. ```ts // import the $enum helper function import { $enum } from "ts-enum-util"; // Example string enum // (basic numeric enums also supported) // (enums with a mix of numeric and string values also supported) enum RGB { R = "r", G = "g", B = "b" } ``` -------------------------------- ### Example: Creating an Enum Subset with createEnumSubset Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md This example demonstrates how to use the `createEnumSubset` method to create a new enum-like object containing only specific entries from an existing enum. It shows the definition of an original enum, the usage of `$enum().createEnumSubset` to filter entries, and how to derive a type for the resulting subset. ```ts enum Numbers { One = 1, Two = 2, Three = 3, Four = 4 } const EvenNumbers = $enum(Numbers).createEnumSubset("Two", "Four"); type EvenNumbers = typeof EvenNumbers[keyof typeof EvenNumbers]; ``` -------------------------------- ### Define RGB Enum for Examples Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/migration_from_ts-string-visitor.md This TypeScript enum `RGB` is used as the `value` type in all subsequent examples to demonstrate string visiting and mapping functionalities. ```ts enum RGB { R = "r", G = "g", B = "b" } ``` -------------------------------- ### Install ts-enum-util via npm Source: https://github.com/uselesspickles/ts-enum-util/blob/master/README.md This command installs the ts-enum-util library as a production dependency in your project using npm. ```shell npm i -s ts-enum-util ``` -------------------------------- ### Migrate String Visitor Functionality Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/migration_from_ts-string-visitor.md This snippet demonstrates how to convert code using `visitString` from `ts-string-visitor` to the equivalent `visitValue` method in `ts-enum-util`. It highlights the change in import and the use of `$enum.unhandledEntry` and `$enum.handle...` keys for handling special values. ```ts import { visitString } from "ts-string-visitor"; visitString(value).with({ [RGB.R]: () => {}, // explicitly unhandled entry [RGB.G]: visitString.unhandled, [RGB.B]: () => {}, handleNull: () => {}, handleUndefined: () => {}, handleUnexpected: () => {} }); ``` ```ts import { $enum } from "ts-enum-util"; $enum.visitValue(value).with({ [RGB.R]: () => {}, // explicitly unhandled entry [RGB.G]: $enum.unhandledEntry, [RGB.B]: () => {}, [$enum.handleNull]: () => {}, [$enum.handleUndefined]: () => {}, [$enum.handleUnexpected]: () => {} }); ``` -------------------------------- ### Get All Enum Entries (getEntries) Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Returns a list of `[key, value]` tuples representing all entries within the enum. Consult the 'Order of Iteration' section for information regarding the sequence of entries. ```ts EnumWrapper.prototype.getEntries(): EnumWrapper.Entry[] ``` -------------------------------- ### Migrate String Mapper Functionality Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/migration_from_ts-string-visitor.md This snippet shows the migration path for `mapString` from `ts-string-visitor` to `mapValue` in `ts-enum-util`. It illustrates how to map values based on enum members and handle special cases like `null`, `undefined`, and unexpected inputs, noting the change in special key handling. ```ts import { mapString } from "ts-string-visitor"; const result = mapString(value).with({ [RGB.R]: 1, // explicitly unhandled entry [RGB.G]: mapString.unhandled, [RGB.B]: 2, handleNull: 3, handleUndefined: 4, handleUnexpected: 5 }); ``` ```ts import { $enum } from "ts-enum-util"; const result = $enum.mapValue(value).with({ [RGB.R]: 1, // explicitly unhandled entry [RGB.G]: $enum.unhandledEntry, [RGB.B]: 2, [$enum.handleNull]: 3, [$enum.handleUndefined]: 4, [$enum.handleUnexpected]: 5 }); ``` -------------------------------- ### TypeScript: Handling Null with $enum.visitValue (Visitor Example) Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumValueVisitor.md Demonstrates how to correctly handle `null` values when using the `$enum.visitValue` method. This example shows a TypeScript function that maps an `RGB` type (which can be `null`) to a string label, requiring the visitor object to include a `[$enum.handleNull]` property. ```typescript type RGB = "r" | "g" | "b"; function getRgbLabel(rgb: RGB | null): string { // The type of 'rgb' includes 'null', so the visitor must // handle null return $enum.visitValue(rgb).with({ r: () => { return "Red"; }, g: () => { return "Green"; }, b: () => { return "Blue"; }, [$enum.handleNull]: () => { return "null"; } }); } const result = getRgbLabel(null); // result === "null" ``` -------------------------------- ### Retrieving Enum Keys, Values, and Entries as Lists Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Demonstrates how to extract various lists from an enum using the `EnumWrapper`. It covers `getKeys()` to get an array of enum keys, `getValues()` for an array of enum values, and `getEntries()` for an array of key-value pair tuples, useful for comprehensive data access. ```ts // type: ("R" | "G" | "B")[] // value: ["R", "G", "B"] const keys = $enum(RGB).getKeys(); // type: RGB[] // value: ["r", "g", "b"] const values = $enum(RGB).getValues(); // List of key/value pair tuples // type: [("R" | "G" | "B"), RGB][] // value: [["R", "r"], ["G", "g"], ["B", "b"]] const entries = $enum(RGB).getEntries(); ``` -------------------------------- ### TypeScript: Handling Null with $enum.mapValue (Mapper Example) Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumValueVisitor.md Illustrates how to manage `null` values when utilizing the `$enum.mapValue` method. This TypeScript example defines a function that maps an `RGB` type (potentially `null`) to a string, demonstrating the necessity of including a `[$enum.handleNull]` property in the mapper object. ```typescript type RGB = "r" | "g" | "b"; function getRgbLabel(rgb: RGB | null): string { // The type of 'rgb' includes 'null', so the mapper must // handle null return $enum.mapValue(rgb).with({ r: "Red", g: "Green", b: "Blue", [$enum.handleNull]: "null" }); } const result = getRgbLabel(null); // result === "null" ``` -------------------------------- ### TypeScript Enum Value Visitor Basic Usage Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumValueVisitor.md This example demonstrates the basic usage of the generalized visitor pattern provided by `ts-enum-util` to convert a string literal union type value (RGB) into a human-readable label. It shows how to use `$enum.visitValue().with()` and define a visitor object with functions for each possible value, ensuring type-safe and exhaustive handling. ```TypeScript import { $enum } from "ts-enum-util"; type RGB = "r" | "g" | "b"; // Example function that uses $enum.visitValue() to convert a RGB value // to a display label function getRgbLabel(rgb: RGB): string { // Pass the value to $enum.visitValue(), and provide a visitor // implementation to $enum.visitValue().with() return $enum.visitValue(rgb).with({ // The visitor must have a function property for every // possible value of the string literal union type. // TypeScript compilation will fail if you miss any values, // or if you include extras that don't exist in the type. r: () => { return "Red"; }, g: () => { // This function is called when "g" is passed in as the // value for 'rgb'. The return value of this function is // returned by $enum.visitValue().with(). return "Green"; }, b: () => { return "Blue"; } }); } const result = getRgbLabel("g"); // result === "Green" ``` -------------------------------- ### Getting the Count of Enum Entries (size and length) Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Shows how to retrieve the total number of entries within an enum using the `EnumWrapper` instance. It demonstrates both the `size` property, which aligns with a Map-like interface, and the `length` property, which aligns with an Array-like interface, both yielding the same count. ```ts // Part of the Map-like interface implementation // type: number // value: 3 const size = $enum(RGB).size; // Part of the Array-like interface implementation // type: number // value: 3 const length = $enum(RGB).length; ``` -------------------------------- ### Get enum values using $enum wrapper Source: https://github.com/uselesspickles/ts-enum-util/blob/master/README.md This example demonstrates how to use the `$enum` wrapper to retrieve all numeric values of the `Color` enum. The `getValues()` method returns a type-safe array of the enum's numeric members. ```typescript // type of "values": Color[] // value of "values": [0, 1, 2] const values = $enum(Color).getValues(); ``` -------------------------------- ### Reverse Lookup: Getting Enum Keys by Value Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Illustrates the process of performing a reverse lookup, finding an enum key given its value. It demonstrates `getKeyOrThrow()` for strict lookups that throw an error if the value is not found, and `getKeyOrDefault()` for flexible lookups that return `undefined` or a specified default key if the value is absent. ```ts // type: ("R" | "G" | "B") // value: "G" const key1 = $enum(RGB).getKeyOrThrow("g"); // throws: Error("Unexpected value: blah. Expected one of: r,g,b") const key2 = $enum(RGB).getKeyOrThrow("blah"); // type: ("R" | "G" | "B") | undefined // value: undefined const key3 = $enum(RGB).getKeyOrDefault("blah"); // type: ("R" | "G" | "B") // value: "R" const key4 = $enum(RGB).getKeyOrDefault("blah", "R"); // type: string // value: "BLAH!" const key4 = $enum(RGB).getKeyOrDefault("blah", "BLAH!"); ``` -------------------------------- ### TypeScript Enum Value Mapper Basic Usage Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumValueVisitor.md This example illustrates the simpler mapper pattern from `ts-enum-util`, used when a direct mapping from a string/number literal union or enum value to another value is needed without complex logic. It demonstrates `$enum.mapValue().with()` where a mapper object directly provides the output value for each input, ensuring type safety and exhaustive mapping. ```TypeScript import { $enum } from "ts-enum-util"; type RGB = "r" | "g" | "b"; // Example function that uses $enum.mapValue() to convert a RGB value // to a display label function getRgbLabel(rgb: RGB): string { // Pass the value to $enum.mapValue(), and provide a mapper // implementation to $enum.mapValue().with() return $enum.mapValue(rgb).with({ // The mapper must have a property for every // possible value of the string literal union type. // TypeScript compilation will fail if you miss any values, // or if you include extras that don't exist in the type. r: "Red", // This propery's value is looked up and returned when // "g" is passed in as the value for 'rgb'. g: "Green", b: "Blue" }); } const result = getRgbLabel("g"); // result === "Green" ``` -------------------------------- ### Map enum values to string labels with $enum.mapValue Source: https://github.com/uselesspickles/ts-enum-util/blob/master/README.md This example demonstrates `$enum.mapValue()` to map enum values to corresponding string labels. It also shows how to handle `undefined` input using `$enum.handleUndefined`, providing a default label for unhandled cases. ```typescript function getColorLabel(color: Color | undefined): string { return $enum.mapValue(color).with({ [Color.R]: "Red", [Color.G]: "Green", [Color.B]: "Blue", [$enum.handleUndefined]: "Unspecified" }); } ``` -------------------------------- ### Define a basic TypeScript enum Source: https://github.com/uselesspickles/ts-enum-util/blob/master/README.md This snippet defines a simple numeric enum named `Color` with three members: `R`, `G`, and `B`. This enum serves as a common example for demonstrating the `ts-enum-util` functionalities. ```typescript enum Color { R, G, B } ``` -------------------------------- ### Accessing Value in ts-enum-util Visitor Methods Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumValueVisitor.md Shows that visitor methods receive the exact value being visited as a parameter, not the broader union type. This example demonstrates an identity visitor that returns the input value, including special handling for `null` and `undefined`. ```ts type RGB = "r" | "g" | "b"; function rgbIdentity(rgb: RGB | null | undefined): RGB | null | undefined { return $enum.visitValue(rgb).with({ r: (value) => { // type of 'value' is exactly "r" // (not RGB | null | undefined) return value; }, g: (value) => { // type of 'value' is exactly "g" return value; }, b: (value) => { // type of 'value' is exactly "b" return value; }, [$enum.handleNull]: (value) => { // type of 'value' is exactly null return value; }, [$enum.handleUndefined]: (value) => { // type of 'value' is exactly undefined return value; } }); } const result = rgbIdentity("g"); // result === "g" ``` -------------------------------- ### Get All Enum Values (getValues) Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Returns an array containing all values present in the enum. If the enum includes duplicate values, the returned array will also contain these duplicates. Refer to the 'Order of Iteration' section for details on the ordering of elements. ```ts EnumWrapper.prototype.getValues(): EnumType[] ``` -------------------------------- ### Mapping TypeScript Enum Values with ts-enum-util Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumValueVisitor.md Explains that `ts-enum-util`'s visitor/mapper functions operate on the *values* of TypeScript enums, not their identifiers. It provides an example demonstrating correct usage by referencing enum values and incorrect usage by referencing identifiers. ```TypeScript enum RGB { // "R" is the name of the identifier. // "r" is the value. R = "r", G = "g", B = "b" } function getRgbLabel(rgb: RGB): string { return $enum.visitValue(rgb).with({ // This works (my preferred style) [RGB.R]: () => { return "Red"; }, // This also works g: () => { return "Green"; }, // This does NOT work! B: () => { return "Blue"; } }); } ``` -------------------------------- ### Get Ordered Index of Enum Key (indexOfKey) Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Returns the ordered index of a specified enum key. This method is useful for implementing comparators based on the enum's iteration order. The `key` parameter must be a valid key of the enum. See 'Order of Iteration' for ordering details. ```ts EnumWrapper.prototype.indexOfKey(key: KeyType): number ``` -------------------------------- ### Handle Unexpected Enum Values with $enum.visitValue in TypeScript Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumValueVisitor.md This example demonstrates how to use the `$enum.handleUnexpected` symbol within a visitor pattern with `$enum.visitValue`. It provides a default return value for any input that does not match the explicitly defined enum members, preventing runtime errors from unexpected external data. ```TypeScript type RGB = "r" | "g" | "b"; function getRgbLabel(rgb: RGB): string { return $enum.visitValue(rgb).with({ r: () => { return "Red"; }, g: () => { return "Green"; }, b: () => { return "Blue"; }, [$enum.handleUnexpected]: () => { return "Unexpected!"; } }); } // Type casting to force an unexpected value at run time const result = getRgbLabel(("blah" as unknown) as RGB); // result === "Unexpected" ``` -------------------------------- ### Get Ordered Index of Enum Value (indexOfValue) Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Returns the ordered index of a specified enum value. This can be used for implementing comparators that rely on the enum's iteration order. The `value` parameter must be a valid value of the enum. See 'Order of Iteration' for ordering details. ```ts EnumWrapper.prototype.indexOfValue(value: EnumType): number ``` -------------------------------- ### Throw Error for Explicitly Unhandled Enum Values with $enum.visitValue in TypeScript Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumValueVisitor.md This example shows how to use `$enum.unhandledEntry` within a visitor pattern with `$enum.visitValue`. By assigning this symbol to an enum member, the system will explicitly throw an error if that specific value is encountered at runtime, indicating it should not be processed. ```TypeScript type RGB = "r" | "g" | "b"; function getRgbLabel(rgb: RGB): string { return $enum.visitValue(rgb).with({ r: () => { return "Red"; }, g: $enum.unhandledEntry, b: () => { return "Blue"; } }); } // Throws error: "Unhandled value: g" const result = getRgbLabel("g"); ``` -------------------------------- ### Obtaining an EnumWrapper Instance with $enum Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Illustrates the fundamental step of using the `$enum` function to create an `EnumWrapper` instance for a particular enum. This wrapped instance provides access to a rich set of utility methods for enum manipulation. ```ts // type: EnumWrapper const wrappedRgb = $enum(RGB); ``` -------------------------------- ### Iterating and Mapping Enum Entries Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Explains how to traverse and transform enum entries using the `EnumWrapper`'s iteration capabilities. It covers `forEach()` for performing an action on each entry and `map()` for converting all entries into a new array, providing access to the value, key, wrapped enum instance, and index during iteration. ```ts const wrappedRgb = $enum(RGB); // iterate all entries in the enum wrappedRgb.forEach((value, key, wrappedEnum, index) => { // type of value is RGB // type of key is ("R" | "G" | "B") // wrappedEnum is a reference to wrappedRgb // index is based on original defined order of the enum }); // Convert all entries of the enum to an array of mapped values // value: ["R: r", "G: g", "B: b"] const mapped = wrappedRgb.map((value, key, wrappedEnum, index) => { // type of value is RGB // type of key is ("R" | "G" | "B") // wrappedEnum is a reference to wrappedRgb // index is based on original defined order of the enum return `${key}: ${value}`; }); ``` -------------------------------- ### EnumWrapper Class API Reference (Map-Like Interface) Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Detailed API documentation for the `EnumWrapper` class, highlighting its properties and methods that mimic the ES6 `Map` interface. It provides a read-only view of enum names and values, enabling various forms of iteration and access. ```APIDOC EnumWrapper Class: Description: Wraps an enum-like object, providing utility methods and a Map-like interface. Properties: size: number Description: The number of entries (key-value pairs) in the wrapped enum. Methods: keys(): IterableIterator Description: Returns an iterable of the keys (enum names) in the wrapped enum. values(): IterableIterator Description: Returns an iterable of the values (enum values) in the wrapped enum. entries(): IterableIterator<[string, any]> Description: Returns an iterable of [key, value] pairs for each entry in the wrapped enum. forEach(callbackfn: (value: any, key: string, wrappedEnum: EnumWrapper, index: number) => void, thisArg?: any): void Description: Executes a provided function once for each key-value pair in the wrapped enum. Parameters: value: The current enum value. key: The current enum name. wrappedEnum: A reference to the EnumWrapper instance. index: The index based on the original defined order of the enum. @@iterator(): IterableIterator<[string, any]> Description: Makes EnumWrapper instances directly iterable, yielding [key, value] pairs. Notes: - The Map interface's has() and get() methods are intentionally NOT implemented. - Equivalent methods are isKey() and getValueOrDefault(). ``` -------------------------------- ### Validating and Converting Enum Keys Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Shows methods for validating if an arbitrary string is a valid enum key and for converting it to a type-safe key. It covers `isKey()` as a type guard, `asKeyOrThrow()` for strict conversion, and `asKeyOrDefault()` for flexible conversion that returns `undefined` or a default key if validation fails. ```ts // Some arbitrary string declare const str: string; // Returns `true` if 'str' is a valid key of RGB if ($enum(RGB).isKey(str)) { // isKey() is a type guard // type of 'str' in here is ("R" | "G" | "B") } // type: ("R" | "G" | "B") // throws error if 'str' is not a valid key for RGB const key1 = $enum(RGB).asKeyOrThrow(str); // type: ("R" | "G" | "B") | undefined // value is undefined if 'str' is not a valid key for RGB const key2 = $enum(RGB).asKeyOrDefault(str); // type: ("R" | "G" | "B") // value is "G" if 'str' is not a valid key for RGB const key3 = $enum(RGB).asKeyOrDefault(str, "G"); ``` -------------------------------- ### API Reference: $enum Function Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Documents the $enum function, the primary entry point for obtaining an EnumWrapper instance from an enum or enum-like object. It highlights the caching mechanism for efficient retrieval and defines its parameters and return type. ```APIDOC function $enum(enumObj: EnumLike): EnumWrapper; Parameters: enumObj: EnumLike - An enum or "enum-like" object. Returns: EnumWrapper - An instance providing utilities for the given enum. ``` -------------------------------- ### Using ts-enum-util with Visitor Method Parameters Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumValueVisitor.md Demonstrates how to use `ts-enum-util`'s visitor pattern while being conscious of parameter types, especially when handling `null` or `undefined` values. It shows how to define specific handlers for different value types to maintain type safety. ```TypeScript type RGB = "r" | "g" | "b"; // test if a color value is "supported" function isSupportedColor(rgb: RGB | null | undefined): boolean { // Since this handler is not used for null/undefined, there's no // need to include those types for the param. // The type technically only needs to be ("r" | "b"), but type // RGB is more convenient and there's no harm in being overly // permissive in this case. const handleSupported = (value: RGB): boolean => { // Since the type 'value' does not include null/undefined, we // can safely call value.toupperCase() without performing a // null check first. // This is an example of why being restrictive with the type // of shared handler can be beneficial. console.log(`handling supported value: ${value.toUpperCase()}`); return true; }; // This handler is used to handle null/undefined, so it MUST // include those types for the param. // Again, the type only technically needs to be // ("g" | null | undefined), but being more permissive can be // more convenient when it's not harmful. const handleUnsupported = (value: RGB | null | undefined): boolean => { console.warn(`unsupported color encountered: ${value}`); return false; }; return $enum.visitValue(rgb).with({ r: handleSupported, // Green is ugly - UNSUPPORTED! g: handleUnsupported, b: handleSupported, [$enum.handleNull]: handleUnsupported, [$enum.handleUndefined]: handleUnsupported }); } ``` -------------------------------- ### APIDOC: $enum.visitValue Method for Visitor Pattern Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumValueVisitor.md Documents the `$enum.visitValue` method, which allows executing functions based on the value of a string/number literal union or enum type. It details the method signature, parameters (`value`, `visitor`), and return type (`result`), along with special handlers for `null` and `undefined` inputs. ```APIDOC Method: $enum.visitValue Signature: [result] = $enum.visitValue([value]).with([visitor]) Parameters: [value]: Type: string | number literal union | enum Description: The value to be visited. [visitor]: Type: object Description: An object where property names match all possible values of [value]'s type. Property values are functions that will be called when the corresponding property name value is passed. Note: Every visitor method must have the same return type. Returns: [result]: Type: Any Description: The value returned by the executed visitor function. Not required to return a value. Special Handlers: [$enum.handleNull]: Type: function Description: Required if [value] may be null. Function to be called for null values. [$enum.handleUndefined]: Type: function Description: Required if [value] may be undefined. Function to be called for undefined values. ``` -------------------------------- ### APIDOC: EnumWrapper.prototype.createEnumSubset Method Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md API documentation for the `createEnumSubset` method. This method is used to generate a new, well-typed 'Enum-Like Object' that contains only a specified subset of entries from the original enum. It allows for creating smaller, focused enum structures from larger ones. ```APIDOC EnumWrapper.prototype.createEnumSubset( ...keys: readonly KeyType[] ): EnumLike ``` -------------------------------- ### Lookup Key by Enum Value or Throw (getKeyOrThrow) Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Performs a reverse lookup to find the key corresponding to the provided `value`. If duplicate values exist, the key for the last duplicate entry (based on 'Order of Iteration') is returned. An `Error` is thrown if the `value` is not valid. ```ts EnumWrapper.prototype.getKeyOrThrow( value: ValueType | null | undefined ): KeyType ``` -------------------------------- ### Looking Up Enum Values by Key Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Explains how to retrieve an enum value based on its corresponding key. It showcases `getValueOrThrow()` for strict lookups that throw an error if the key is not found, and `getValueOrDefault()` for flexible lookups that return `undefined` or a specified default value if the key is absent. ```ts // type: RGB // value: "g" const value1 = $enum(RGB).getValueOrThrow("G"); // throws: Error("Unexpected value: blah. Expected one of: R,G,B") const value2 = $enum(RGB).getValueOrThrow("blah"); // type: RGB | undefined // value: undefined const value3 = $enum(RGB).getValueOrDefault("blah"); // type: RGB // value: "r" const value4 = $enum(RGB).getValueOrDefault("blah", RGB.R); // type: string // value: "BLAH!" const value5 = $enum(RGB).getValueOrDefault("blah", "BLAH!"); ``` -------------------------------- ### Lookup Key by Enum Value or Return Default (getKeyOrDefault) Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Performs a reverse lookup to find the key corresponding to the provided `value`. If duplicate values exist, the key for the last duplicate entry (based on 'Order of Iteration') is returned. If the `value` is not valid, `defaultKey` is returned. This method is overloaded to provide the most specific return type based on the `defaultKey` parameter's type. ```ts EnumWrapper.prototype.getKeyOrDefault( value: ValueType | null | undefined, defaultKey?: KeyType | string ): KeyType | string | undefined ``` -------------------------------- ### Share ts-enum-util Visitor Methods Without Parameters Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumValueVisitor.md Explains how to reuse visitor methods across multiple enum values when the shared logic does not depend on the specific value being visited. This improves code reusability and maintainability. ```ts type RGB = "r" | "g" | "b"; // test if a color value is "supported" function isSupportedColor(rgb: RGB | null | undefined): boolean { // pre-define a handler for all "supported" values const handleSupported = (): boolean => { return true; }; // pre-defined a handler for all "unsupported" values const handleUnsupported = (): boolean => { return false; }; return $enum.visitValue(rgb).with({ r: handleSupported, // Green is ugly - UNSUPPORTED! g: handleUnsupported, b: handleSupported, [$enum.handleNull]: handleUnsupported, [$enum.handleUndefined]: handleUnsupported }); } ``` -------------------------------- ### Cast to Enum Key or Return Default (asKeyOrDefault) Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md If the provided `key` is a valid enum key, it is returned, cast to `KeyType`. Otherwise, the `defaultKey` is returned. This method is overloaded to provide the most specific return type based on the `defaultKey` parameter's type. ```ts EnumWrapper.prototype.asKeyOrDefault( key: string | null | undefined, defaultKey?: KeyType | string ): KeyType | string | undefined ``` -------------------------------- ### APIDOC: $enum.mapValue Method for Mapper Pattern Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumValueVisitor.md Documents the `$enum.mapValue` method, which simplifies converting a string/number literal union or enum type into another value. It outlines the method signature, parameters (`value`, `mapper`), and return type (`result`), including how to handle `null` and `undefined` inputs. ```APIDOC Method: $enum.mapValue Signature: [result] = $enum.mapValue([value]).with([mapper]) Parameters: [value]: Type: string | number literal union | enum Description: The value to be mapped. [mapper]: Type: object Description: An object where property names match all possible values of [value]'s type. Property values are the mapped values that will be returned. Note: Every property of your mapper must be of the same type. Returns: [result]: Type: Any Description: The value of whichever [mapper] property matched [value]. Special Handlers: [$enum.handleNull]: Type: Any Description: Required if [value] may be null. The value to be returned for null inputs. [$enum.handleUndefined]: Type: Any Description: Required if [value] may be undefined. The value to be returned for undefined inputs. ``` -------------------------------- ### EnumWrapper.prototype.entries() Method Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Returns an `Iterator` that can be used to iterate over all `[key, value]` pairs (entries) in the enum. ```typescript EnumWrapper.prototype.entries(): IterableIterator ``` -------------------------------- ### Validating and Converting Enum Values Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Demonstrates methods for validating if an arbitrary string is a valid enum value and for converting it to a type-safe enum value. It includes `isValue()` as a type guard, `asValueOrThrow()` for strict conversion, and `asValueOrDefault()` for flexible conversion that returns `undefined` or a default value if validation fails. ```ts // Some arbitrary string declare const str: string; // Returns `true` if 'str' is a valid value of RGB if ($enum(RGB).isValue(str)) { // isValue() is a type guard // type of 'str' in here is RGB } // type: RGB // throws error if 'str' is not a valid value for RGB const value1 = $enum(RGB).asValueOrThrow(str); // type: RGB | undefined // value is undefined if 'str' is not a valid value for RGB const value2 = $enum(RGB).asValueOrDefault(str); // type: RGB // value is RGB.G if 'str' is not a valid value for RGB const value3 = $enum(RGB).asValueOrDefault(str, RGB.G); ``` -------------------------------- ### EnumWrapper.prototype.@@iterator() Method Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Allows an `EnumWrapper` instance to be directly iterated as a collection of `[key, value]` tuples, behaving identically to `EnumWrapper.prototype.entries()`. ```typescript EnumWrapper.prototype.@@iterator(): IterableIterator ``` -------------------------------- ### Explicitly Define Visitor Return Type with ts-enum-util Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumValueVisitor.md Demonstrates how to use a template parameter with `$enum.visitValue().with()` to explicitly set the expected return type of a visitor, ensuring compile-time type checking and preventing confusing type inference errors. ```ts type RGB = "r" | "g" | "b"; function getRgbLabel(rgb: RGB): string { // Tell the compiler that you intend to return a string from the // visitor return $enum.visitValue(rgb).with({ // Compiler error for this property r: () => { return 10; }, g: () => { return "Green"; }, b: () => { return "Blue"; } }); } ``` -------------------------------- ### EnumWrapper.prototype.getKeys() Method Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Returns a new array containing all the keys extracted from the enum. ```typescript EnumWrapper.prototype.getKeys(): KeyType[] ``` -------------------------------- ### EnumWrapper.prototype.keys() Method Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Returns an `Iterator` that can be used to iterate over all the keys present in the enum. ```typescript EnumWrapper.prototype.keys(): IterableIterator ``` -------------------------------- ### Cast to Enum Key or Throw Error (asKeyOrThrow) Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md If the provided `key` is a valid enum key, it is returned, cast to the more specific `KeyType`. If the `key` is not valid, an `Error` is thrown. ```ts EnumWrapper.prototype.asKeyOrThrow( key: string | null | undefined ): KeyType ``` -------------------------------- ### APIDOC: EnumWrapper.prototype.getValueOrThrow Method Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md API documentation for the `getValueOrThrow` method. This method returns the enum value corresponding to the provided `key`. If the `key` is not valid, an `Error` is thrown, ensuring type safety and explicit error handling. ```APIDOC EnumWrapper.prototype.getValueOrThrow( key: string | null | undefined ): EnumType ``` -------------------------------- ### EnumWrapper.prototype.forEach() Method Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Iterates through every entry in the enum and invokes the provided `iteratee` function for each. The return value of the `iteratee` is ignored. An optional `context` can be supplied to set the `this` binding for the `iteratee` function. ```typescript EnumWrapper.prototype.forEach( iteratee: EnumWrapper.Iteratee, context?: any ): void ``` -------------------------------- ### EnumWrapper.prototype.size Property Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md A read-only property that indicates the number of entries in the enum, providing a map-like interface for querying the collection size. ```typescript readonly EnumWrapper.prototype.size: number ``` -------------------------------- ### Iterating and Accessing Wrapped Enum Properties as Map-Like (TypeScript) Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Illustrates how a wrapped enum (EnumWrapper) functions similarly to a read-only Map, providing methods for size, iteration over keys, values, or entries, and a forEach method. This allows for convenient traversal and processing of enum members. ```typescript const wrappedRgb = $enum(RGB); // type: number // value: 3 const size = wrappedRgb.size; // EnumWrapper is directly iterable like a Map for (const [key, value] of wrappedRgb) { // type of key: ("R" | "G" | "B") // type of value: RGB } for (const key of wrappedRgb.keys()) { // type of key: ("R" | "G" | "B") } for (const value of wrappedRgb.values()) { // type of value: RGB } wrappedRgb.forEach((value, key, wrappedEnum, index) => { // type of value is RGB // type of key is ("R" | "G" | "B") // wrappedEnum is a reference to wrappedRgb // index is based on original defined order of the enum // NOTE: index param is extra compared to Map's forEach }); ``` -------------------------------- ### Accessing Wrapped Enum Properties as Array-Like (TypeScript) Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Demonstrates how a wrapped enum (EnumWrapper) behaves like a read-only array, allowing access to its length and individual entries by index. Each entry is a tuple containing the enum key and its corresponding value. ```typescript const wrappedRgb = $enum(RGB); // type: number // value: 3 const length = wrappedRgb.length; // type: [("R" | "G" | "B"), RGB] // value: ["G", "g"] const entry = wrappedRgb[1]; ``` -------------------------------- ### EnumWrapper.prototype.[index] Index Signature Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Implements an index signature on `EnumWrapper` instances, allowing access to `[key, value]` tuples by numerical index, similar to array indexing. The accessed values are read-only. ```typescript readonly EnumWrapper.prototype.[index: number]: EnumWrapper.Entry ``` -------------------------------- ### EnumWrapper.prototype.map() Method Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md Creates and returns a new array by applying the provided `iteratee` function to each entry in the enum. The generic type `R` specifies the type of elements in the resulting array, inferred if not explicitly provided. An optional `context` can be supplied to set the `this` binding for the `iteratee` function. ```typescript EnumWrapper.prototype.map( iteratee: EnumWrapper.Iteratee, context?: any ): R[] ``` -------------------------------- ### EnumWrapper Class Definition Source: https://github.com/uselesspickles/ts-enum-util/blob/master/docs/EnumWrapper.md The core class that implements all enum utilities. It is a generic class with a private constructor, intended to be instantiated via the `$enum()` helper function. ```typescript class EnumWrapper ```