Skip to content

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 ParameterDefault typeDescription
Config extends string | TaggedTypes-The configuration object or array of tags
TagProp extends string"tag"The property name used for the tag (default: “tag”)
RMatchboxFactory<Config extends readonly string[] ? { [K in string]: (data: any) => any } : Config, TagProp>-
ParameterType
configConfig
tagPropTagProp

R

An object with constructors for each variant, type predicates, and match function

// Define a union of variants for a Result type
const Result = matchboxFactory({
Ok: (value: number) => ({ value }),
Err: (error: string) => ({ error }),
});
// Create instances
const ok = Result.Ok(42);
const err = Result.Err("fail");
// Type predicates
ok.is("Ok"); // true
err.is("Err"); // true
// Pattern matching
const message = ok.match({
Ok: ({ value }) => `Value: ${value}`,
Err: ({ error }) => `Error: ${error}`,
});
// message === "Value: 42"