matchboxFactory
matchboxFactory<
Config
,TagProp
,R
>(config
:Config
,tagProp
:TagProp
):R
Defined in: matchbox-factory.ts:40
Create a tagged union from a record mapping tags to value types, along with associated
variant constructors, type predicates and match
function.
Type Parameters
Section titled “Type Parameters”Type Parameter | Default type | Description |
---|---|---|
Config extends string | TaggedTypes | - | The configuration object or array of tags |
TagProp extends string | "tag" | The property name used for the tag (default: “tag”) |
R | MatchboxFactory <Config extends readonly string [] ? { [K in string]: (data: any) => any } : Config , TagProp > | - |
Parameters
Section titled “Parameters”Parameter | Type |
---|---|
config | Config |
tagProp | TagProp |
Returns
Section titled “Returns”R
An object with constructors for each variant, type predicates, and match function
Example
Section titled “Example”// Define a union of variants for a Result typeconst Result = matchboxFactory({ Ok: (value: number) => ({ value }), Err: (error: string) => ({ error }),});
// Create instancesconst ok = Result.Ok(42);const err = Result.Err("fail");
// Type predicatesok.is("Ok"); // trueerr.is("Err"); // true
// Pattern matchingconst message = ok.match({ Ok: ({ value }) => `Value: ${value}`, Err: ({ error }) => `Error: ${error}`,});// message === "Value: 42"