Skip to main content
Version: 3.0.0-dev 🔨

variant

Type aliases​

Flags​

Ƭ Flags<T>: Partial<Matrix<T>>

Turn a sum type (a variant) into a partial product type.

see Matrix

Type parameters​

NameType
Textends VariantModule<string>

Defined in​

flags.ts:15


GVariantOf​

Ƭ GVariantOf<VM, TType, Map>: TType extends keyof VM ? Generify<GenericVariantTypeSpread<VM>[TType], Map> : Generify<GenericVariantTypeSpread<VM>[keyof VM], Map>

Generic Variant Of.

Type parameters​

NameType
VMextends GenericVariantRecord<{}, string>
TTypeextends TypeNames<VM>
Mapextends Object

Defined in​

generic.ts:70


Matrix​

Ƭ Matrix<T>: { [P in TypesOf<T>]: CreatorOutput<T[GetTypeLabel<T, P>]> }

Transform a sum type (a variant) into a product type.

Type parameters​

NameType
Textends VariantModule<string>

Defined in​

flags.ts:6


TypeCatalog​

Ƭ TypeCatalog<T>: { [P in TypesOf<T>]: P }

A catalog object listing the types inherent to some VariantModule

Type parameters​

NameType
Textends VariantModule<string>

Defined in​

typeCatalog.ts:7


TypeMap​

Ƭ TypeMap<T>: { [P in keyof T]: T[P]["output"]["type"] }

A mapping of friendly names to the underlying type literals.

remarks Most VariantModules will have labels (Animal.dog) that match the underlying type of the object the function will create. Some will not. This type creates a mapping from the name/label to the type.

Type parameters​

NameType
Textends VariantModule<string>

Defined in​

precepts.ts:107


TypeNames​

Ƭ TypeNames<T>: TypesOf<T> | undefined

Get the literal union for a variant type's names, plus undefined.

Type parameters​

NameType
Textends VariantModule<string>

Defined in​

precepts.ts:139


TypesOf​

Ƭ TypesOf<T>: TypeMap<T>[keyof T]

Get the literal union for a variant's type property.

Type parameters​

NameType
Textends VariantModule<string>

Defined in​

precepts.ts:134


Variant​

Ƭ Variant<Type, Fields, Key>: Record<Key, Type> & Fields

Used in writing cases of a type-first variant.

Variant<'One', {a: number, b: string}>> generates

  • {type: 'One', a: number, b: string}

You may write the literals directly, using this is recommended if you'd like to update the literal as this library updates.

Type parameters​

NameType
Typeextends string
Fieldsextends Object = {}
Keyextends string = "type"

Defined in​

precepts.ts:12


VariantModule​

Ƭ VariantModule<K>: Object

A variant module definition. Literally an object serving as a collection of variant constructors.

Type parameters​

NameType
Kextends string

Index signature​

â–ª [name: string]: VariantCreator<string, Func, K>

Defined in​

precepts.ts:95


VariantOf​

Ƭ VariantOf<T, TType>: TType extends undefined ? SumType<T> : TType extends TypesOf<T> ? Extract<SumType<T>, Record<T[keyof T][``"output"``]["key"], TType>> : SumType<T>

Create a variant type.

example

ts
// full form
export type SomeVariant<T extends TypeNames<typeof SomeVariant> = undefined>
= VariantOf<typeof SomeVariant, T>;
// short form (no Animal<'cat'>)
export type SomeVariant = VariantOf<typeof SomeVariant>;
ts
// full form
export type SomeVariant<T extends TypeNames<typeof SomeVariant> = undefined>
= VariantOf<typeof SomeVariant, T>;
// short form (no Animal<'cat'>)
export type SomeVariant = VariantOf<typeof SomeVariant>;

Type parameters​

NameType
Textends VariantModule<string>
TTypeundefined

Defined in​

precepts.ts:166

Functions​

HOI​

â–¸ Const HOI<Constraint>(): <T>(definition: T) => T

Higher-Order Identity.

A higher order factory for this very useful wrapper function.

ts
// Enforce the type constraint *and* narrow the return type.
function defineThing<T extends Template>(definition: T): T {
return definition;
}
ts
// Enforce the type constraint *and* narrow the return type.
function defineThing<T extends Template>(definition: T): T {
return definition;
}

The above defineThing can now be generated through

ts
const defineThing = HOI<Template>();
ts
const defineThing = HOI<Template>();

Or in more advanced to define something like a catalog:

ts
const defineThings = HOI<Record<string, Template>>();
ts
const defineThings = HOI<Record<string, Template>>();

Type parameters​

Name
Constraint

Returns​

fn

â–¸ <T>(definition): T

Type parameters​
Name
T
Parameters​
NameType
definitionT
Returns​

T

Defined in​

util.ts:60


augment​

â–¸ augment<T, F>(variantDefinition, f): AugmentedRawVariant<T, F>

Augment an existing variant model with new or overridden fields.

tutorial Use in conjunction with variant (or variantModule).

typescript
// Add a timestamp to every action.
export const Action = variant(augment(
{
AddTodo: fields<{text: string, due?: number}>(),
UpdateTodo: fields<{todoId: number, text?: string, due?: number, complete?: boolean}>(),
},
() => ({timestamp: Date.now()}),
));
typescript
// Add a timestamp to every action.
export const Action = variant(augment(
{
AddTodo: fields<{text: string, due?: number}>(),
UpdateTodo: fields<{todoId: number, text?: string, due?: number, complete?: boolean}>(),
},
() => ({timestamp: Date.now()}),
));

Type parameters​

NameType
Textends RawVariant
Fextends (x: Identity<VariantTypeSpread<VariantRecord<T, string>>[keyof T]>) => any

Parameters​

NameTypeDescription
variantDefinitionTa template for the variant, extends RawVariant, may be an existing variant.
fFthe augment function. This receives the object that is is augmenting, enabling calculated properties.

Returns​

AugmentedRawVariant<T, F>

Defined in​

augment.ts:25


catalog​

â–¸ catalog<T>(strings): { [P in T]: P }

Create a catalog object from a set of strings.

tutorial

ts
const Suit = catalog(['Spades', 'Hearts', 'Clubs', 'Diamonds']);
type Suit = keyof typeof Suit;
ts
const Suit = catalog(['Spades', 'Hearts', 'Clubs', 'Diamonds']);
type Suit = keyof typeof Suit;

Suit is now available as both value (return Suit.Spades) and type (function(cardSuit: Suit) { ... })

Type parameters​

NameType
Textends string

Parameters​

NameTypeDescription
stringsT[](string[]) - list of string literals

Returns​

{ [P in T]: P }

a string enum

Defined in​

catalog.ts:40

â–¸ catalog<T, F>(strings, factory): { [P in T]: ReturnType<F> }

Create a catalog object based on some calculation

tutorial

ts
const logLevels = catalog(
['trace', 'debug', 'info', 'warn', 'error', 'fatal'],
(_, index) => index * 100, // 100 as buffer.
);
ts
const logLevels = catalog(
['trace', 'debug', 'info', 'warn', 'error', 'fatal'],
(_, index) => index * 100, // 100 as buffer.
);

This generates a catalog object:

const logLevels = { trace: 0, debug: 100, info: 200, ..., };

Something like logLevels is commonly used as the internal representation for a logger. The minimum log level (or threshold) is a simple number that we can use for comparison against this table. The 100 is purely a convention to allow future items to slide in- between existing values.

Type parameters​

NameType
Textends string
Fextends LiteralFactory<T>

Parameters​

NameTypeDescription
stringsT[]list of string literals.
factoryFfunction to generate value.

Returns​

{ [P in T]: ReturnType<F> }

an enum or constant mapping where the values are based on the factory function.

Defined in​

catalog.ts:69

â–¸ catalog<T>(catalog): T

Define the catalog object manually.

Use to enforce a consistent type for all values.

tutorial

ts
const settingKey = catalog({
one: 'SETTING_ONE',
two: 'SETTING_TWO',
} as const);
ts
const settingKey = catalog({
one: 'SETTING_ONE',
two: 'SETTING_TWO',
} as const);

Type parameters​

NameType
Textends LiteralCatalog

Parameters​

NameTypeDescription
catalogTan object literal where each value is the same type of literal.

Returns​

T

Defined in​

catalog.ts:85


constant​

â–¸ constant<T>(x): () => T

Create a function that returns a value after being called.

Type parameters​

Name
T

Parameters​

NameTypeDescription
xTthe value to be returned

Returns​

fn

â–¸ (): T

Returns​

T

Defined in​

match.tools.ts:6


constrained​

â–¸ constrained<T, F>(_constraint_, v): PatchedTemplate<T, F>

Constrained variant. A variant where each form abides by a given constraint - handles these inputs and provides these outputs.

This can be used to ensure optional properties exist on the union type.

Type parameters​

NameType
Textends ConstrainedTemplate<F>
Fextends Func

Parameters​

NameType
_constraint_F
vT

Returns​

PatchedTemplate<T, F>

Defined in​

constrained.ts:25


construct​

â–¸ construct<T>(cls): ConstructableToFactory<T>

Create a variant based on a class.

Type parameters​

NameType
Textends Constructable

Parameters​

NameTypeDescription
clsTclass definition / constructor

Returns​

ConstructableToFactory<T>

a variant creator that wraps the class constructor into a factory function.

Defined in​

construct.ts:14


descope​

â–¸ descope<T>(target): T extends Record<"type", `${string}/${TType}`> ? Identity<Omit<T, "type"> & Record<"type", TType>> : T

Strip the scope prefix from an object passed into match

tutorial

ts
match(descope(target), {
...,
})
ts
match(descope(target), {
...,
})

Type parameters​

NameType
Textends Record<"type", `${string}/${string}`>

Parameters​

NameTypeDescription
targetTobject used as the match target.

Returns​

T extends Record<"type", `${string}/${TType}`> ? Identity<Omit<T, "type"> & Record<"type", TType>> : T

Defined in​

variant.ts:77


fields​

â–¸ fields<T>(defaults?): (...args: {} extends T ? [] | [input: T] : [input: T]) => T

Describe the fields of the variation.

When used creates a function of type (input: T) => T & {type: 'literal'}

Type parameters​

NameType
Textends Object

Parameters​

NameTypeDescription
defaultsPartial<T>set some default values for the object. Note this does not adjust the return type.

Returns​

fn

â–¸ (...args): T

Parameters​
NameType
...args{} extends T ? [] | [input: T] : [input: T]
Returns​

T

Defined in​

variant.tools.ts:8


flags​

â–¸ flags<T>(flags): { [P in string]: Extract<T, Record<"type", P>> }

Turn a list of sum type instances (variants) into a product type.

In other words, perform a unique groupBy on the list, grouping on the type property.

Type parameters​

NameTypeDescription
Textends Record<"type", string>The discriminated union

Parameters​

NameTypeDescription
flagsT[]An array of variant instances.

Returns​

{ [P in string]: Extract<T, Record<"type", P>> }

An object where each property's key is a type string and its value is the instance of that type.

Defined in​

flags.ts:26


inferTypes​

â–¸ inferTypes<T>(instance): { [P in string]: P }

Create a type catalog from an instance of a variant.

Note this leverages proxies and is based on the perceived type union for instance

Type parameters​

NameTypeDescription
Textends Record<"type", string>target discriminated union

Parameters​

NameType
instanceT

Returns​

{ [P in string]: P }

a proxy TypeCatalog

Defined in​

types.ts:36


isOfVariant​

â–¸ isOfVariant<T>(instance, variant): instance is Identity<VariantTypeSpread<T>[keyof T]>

Checks if an object was created from one of a set of variants. This function is a user-defined type guard so TypeScript will narrow the type of object correctly.

remarks The variant module may be a pre-existing module or one constructed on the fly.

Type parameters​

NameType
Textends VariantModule<"type">

Parameters​

NameTypeDescription
instanceundefined | null | {}an instance of a variant.
variantTthe variant module.

Returns​

instance is Identity<VariantTypeSpread<T>[keyof T]>

instance is variant

Defined in​

isOfVariant.ts:18

â–¸ isOfVariant<T>(variant): (instance: undefined | null | {}) => instance is Identity<VariantTypeSpread<T>[keyof T]>

Checks if an object was created from one of a set of variants. This function is a user-defined type guard so TypeScript will narrow the type of object correctly.

remarks The variant module may be a pre-existing module or one constructed on the fly.

Type parameters​

NameType
Textends VariantModule<"type">

Parameters​

NameTypeDescription
variantTthe variant model.

Returns​

fn

user-defined type guard.

â–¸ (instance): instance is Identity<VariantTypeSpread<T>[keyof T]>

Checks if an object was created from one of a set of variants. This function is a user-defined type guard so TypeScript will narrow the type of object correctly.

remarks The variant module may be a pre-existing module or one constructed on the fly.

Parameters​
NameType
instanceundefined | null | {}
Returns​

instance is Identity<VariantTypeSpread<T>[keyof T]>

user-defined type guard.

Defined in​

isOfVariant.ts:30


isType​

â–¸ isType<T>(type): <O>(object: O) => object is Extract<O, Record<"type", TypeStr<T, "type">>>

Check if an object is a variant of some type.

Type parameters​

NameType
Textends string | VariantCreator<string, Func, "type">

Parameters​

NameTypeDescription
typeTany type string or variant creator

Returns​

fn

A user-defined type guard indicating if the instance is of a given type.

â–¸ <O>(object): object is Extract<O, Record<"type", TypeStr<T, "type">>>

Check if an object is a variant of some type.

Type parameters​
NameType
Oextends Record<"type", string>
Parameters​
NameType
objectO
Returns​

object is Extract<O, Record<"type", TypeStr<T, "type">>>

A user-defined type guard indicating if the instance is of a given type.

Defined in​

isType.ts:10

â–¸ isType<O, T>(object, type): object is Extract<O, Record<"type", TypeStr<T, "type">>>

Check if an object is a variant of some type.

Type parameters​

NameType
Oextends Record<"type", string>
Textends string | VariantCreator<O["type"], Func, "type">

Parameters​

NameTypeDescription
objectundefined | null | Oan instance of an object
typeTany type string or variant creator

Returns​

object is Extract<O, Record<"type", TypeStr<T, "type">>>

A user-defined type guard indicating if the instance is of a given type.

Defined in​

isType.ts:17


just​

â–¸ Const just<T>(x): () => T

Type parameters​

Name
T

Parameters​

NameType
xT

Returns​

fn

â–¸ (): T

Returns​

T

Defined in​

match.tools.ts:9


literalist​

â–¸ Const literalist<T>(strings): { [P in T]: P }

Alias for compatibility

deprecated - use catalog

Type parameters​

NameType
Textends string

Parameters​

NameType
stringsT[]

Returns​

{ [P in T]: P }

Defined in​

catalog.ts:103

â–¸ Const literalist<T, F>(strings, factory): { [P in T]: ReturnType<F> }

Alias for compatibility

deprecated - use catalog

Type parameters​

NameType
Textends string
Fextends LiteralFactory<T>

Parameters​

NameType
stringsT[]
factoryF

Returns​

{ [P in T]: ReturnType<F> }

Defined in​

catalog.ts:103

â–¸ Const literalist<T>(catalog): T

Alias for compatibility

deprecated - use catalog

Type parameters​

NameType
Textends LiteralCatalog

Parameters​

NameType
catalogT

Returns​

T

Defined in​

catalog.ts:103


lookup​

â–¸ lookup<H, T>(handler): (instance: T) => LookupTableToHandler<H>

Resolve the match with a lookup table.

Type parameters​

NameType
Hextends Record<T["type"], any>
Textends Record<"type", string>

Parameters​

NameType
handlerH

Returns​

fn

â–¸ (instance): LookupTableToHandler<H>

Resolve the match with a lookup table.

Parameters​
NameType
instanceT
Returns​

LookupTableToHandler<H>

Defined in​

match.ts:84


match​

â–¸ match<T, H, TType>(handler): (instance: T | TType) => ReturnType<H[keyof H]>

(inline) Match an instance of a variant or literal union against its possible cases.

remarks This point-free overload is intended for inline use, not pre-matching.

Type parameters​

NameTypeDescription
Textends Record<"type", TType>instance of a variant
Hextends Handler<T, "type">handler object
TTypeextends string-

Parameters​

NameTypeDescription
handlerEnforceHandler<H> | (t: T) => Ha handler object. This type will be properly constrained when used inline.

Returns​

fn

â–¸ (instance): ReturnType<H[keyof H]>

(inline) Match an instance of a variant or literal union against its possible cases.

remarks This point-free overload is intended for inline use, not pre-matching.

Parameters​
NameType
instanceT | TType
Returns​

ReturnType<H[keyof H]>

Defined in​

match.ts:134

â–¸ match<C, H>(handler): (instance: C) => ReturnType<H[keyof H]>

(inline) Match a variant creator against the constructors it contains.

remarks This point-free overload is intended for inline use, not pre-matching.

Type parameters​

NameTypeDescription
Cextends VariantCreator<string, (...args: any[]) => {}, "type">-
Hextends CreatorHandler<C>handler object

Parameters​

NameTypeDescription
handlerEnforceHandler<H> | (t: C) => Ha handler object. This type will be properly constrained when used inline.

Returns​

fn

â–¸ (instance): ReturnType<H[keyof H]>

(inline) Match a variant creator against the constructors it contains.

remarks This point-free overload is intended for inline use, not pre-matching.

Parameters​
NameType
instanceC
Returns​

ReturnType<H[keyof H]>

Defined in​

match.ts:149

â–¸ match<T, H, TType>(target, handler): ReturnType<H[T["type"]]>

Match an instance of a variant or literal union against its possible cases.

remarks Supports exhaustiveness checking, partial matching, and literals.

Type parameters​

NameType
Textends Record<"type", TType>
Hextends Handler<T, "type">
TTypeextends string

Parameters​

NameTypeDescription
targetT | TTypethe target instance
handlerH | (t: T) => Han object with a function corresponding to each case

Returns​

ReturnType<H[T["type"]]>

The result of the appropriate branch based on the instance type

Defined in​

match.ts:163

â–¸ match<C, H>(target, handler): ReturnType<H[C["output"][``"type"``]]>

Match a variant creator against the constructors it contains.

remarks Supports exhaustiveness checking, partial matching, and literals.

Type parameters​

NameType
Cextends VariantCreator<string, (...args: any[]) => {}, "type">
Hextends CreatorHandler<C>

Parameters​

NameTypeDescription
targetCthe variant creator
handlerH | (t: C) => Han object with a function corresponding to each case

Returns​

ReturnType<H[C["output"][``"type"``]]>

The result of the appropriate branch based on the creator type

Defined in​

match.ts:179


matcher​

â–¸ matcher<T, TType>(target): Matcher<T, "type", {}>

Create a matcher on some target variant instance.

Type parameters​

NameType
Textends Record<"type", string>
TTypeextends string

Parameters​

NameType
targetT | TType

Returns​

Matcher<T, "type", {}>

Defined in​

matcher.ts:323


nil​

â–¸ Const nil(): Object

Create an empty variation ({type: 'literal'}).

Returns​

Object

Defined in​

variant.tools.ts:29


ofLiteral​

â–¸ ofLiteral<T>(instance): LiteralToUnion<T, "type">

Create a variant from a catalog or enum. In other words, elevate a literal A | B | C to a type union {type: A} | {type: B} | {type: C}

Type parameters​

NameType
Textends string | number | symbol

Parameters​

NameType
instanceT

Returns​

LiteralToUnion<T, "type">

Defined in​

match.ts:52


onLiteral​

â–¸ onLiteral<T>(instance): LiteralToUnion<T, "type">

Elevate a literal A | B | C to a type union {type: A} | {type: B} | {type: C}

deprecated use ofLiteral

Type parameters​

NameType
Textends string | number | symbol

Parameters​

NameType
instanceT

Returns​

LiteralToUnion<T, "type">

Defined in​

match.ts:59


onTerms​

â–¸ onTerms<T>(func): GenericTemplate<T>

Define a generic variant

Type parameters​

NameType
Textends RawVariant

Parameters​

NameTypeDescription
func(alpha: Alpha) => Ta template factory. Receives 26 generic placeholders (A-Z) in an object, returns a variant template

Returns​

GenericTemplate<T>

A variant with generic creators

Defined in​

generic.ts:20


otherwise​

â–¸ otherwise<P, T, Else>(branches, elseFunc): (input: T) => HandlerFromPartial<P & { default: Else }, T["type"]>

Handle some cases, deal with the rest in a well-typed function. If the discriminated union is A | B | C and A has been handled, then the else function will understand it will receive only B | C.

Type parameters​

NameType
Pextends Partial<Handler<T, "type">>
Textends Record<"type", string>
Elseextends (remainder: Exclude<T, Record<"type", keyof P>>) => any

Parameters​

NameType
branchesP
elseFuncElse

Returns​

fn

â–¸ (input): HandlerFromPartial<P & { default: Else }, T["type"]>

Handle some cases, deal with the rest in a well-typed function. If the discriminated union is A | B | C and A has been handled, then the else function will understand it will receive only B | C.

Parameters​
NameType
inputT
Returns​

HandlerFromPartial<P & { default: Else }, T["type"]>

Defined in​

match.ts:68


partial​

â–¸ partial<H, T>(handler): (input: T) => H

Handle some cases, use default: to handle the remainder.

Type parameters​

NameType
Hextends AdvertiseDefault<Handler<T, "type">>
Textends Record<"type", string>

Parameters​

NameType
handlerH | (t: T) => H

Returns​

fn

â–¸ (input): H

Handle some cases, use default: to handle the remainder.

Parameters​
NameType
inputT
Returns​

H

Defined in​

match.ts:117

â–¸ partial<H, T>(handler): (input: T) => HandlerFromPartial<H, T["type"]>

Handle some cases, use default: to handle the remainder (Active).

Type parameters​

NameType
Hextends WithDefault<Handler<T, "type">, T>
Textends Record<"type", string>

Parameters​

NameType
handlerH | (t: T) => H

Returns​

fn

â–¸ (input): HandlerFromPartial<H, T["type"]>

Handle some cases, use default: to handle the remainder (Active).

Parameters​
NameType
inputT
Returns​

HandlerFromPartial<H, T["type"]>

Defined in​

match.ts:121


pass​

â–¸ Const pass<T>(x): T

A helper function for variantModule.

This is the identity function by a better name.

Type parameters​

Name
T

Parameters​

NameType
xT

Returns​

T

Defined in​

typed.ts:25


patterned​

â–¸ patterned<T, F>(_constraint_, v): PatchedTemplate<T, F>

Type parameters​

NameType
Textends PatternedTemplate<F>
Fextends Func

Parameters​

NameType
_constraint_F
vT

Returns​

PatchedTemplate<T, F>

Defined in​

patterned.ts:15


payload​

â–¸ payload<T>(_example?): (payload: T) => { payload: T }

Take a single variable of type T and store as 'payload'

Type parameters​

Name
T

Parameters​

NameType
_example?T

Returns​

fn

â–¸ (payload): Object

Parameters​
NameType
payloadT
Returns​

Object

NameType
payloadT

Defined in​

variant.tools.ts:21


prematch​

â–¸ prematch<T>(variant): TypedCurriedMatchFunc<Identity<VariantTypeSpread<T>[keyof T]>, "type">

Match against a variant model

Type parameters​

NameType
Textends VariantModule<"type">

Parameters​

NameTypeDescription
variantTan object containing variant creators.

Returns​

TypedCurriedMatchFunc<Identity<VariantTypeSpread<T>[keyof T]>, "type">

a function to handle an instance of that type.

Defined in​

match.ts:198

â–¸ prematch<T>(): TypedCurriedMatchFunc<T, "type">

Match against a variant by type

Type parameters​

NameTypeDescription
Textends Record<"type", string>a discriminated union

Returns​

TypedCurriedMatchFunc<T, "type">

a function to handle an instance of that type.

Defined in​

match.ts:205


remote​

â–¸ remote<T>(variant): Remote<T, "type">

Create a "remote control" for a variant.

Type parameters​

NameType
Textends VariantModule<"type">

Parameters​

NameType
variantT

Returns​

Remote<T, "type">

Defined in​

remote.ts:116


scoped​

â–¸ scoped<T, Scope>(scope, v): ScopedVariant<T, Scope>

Type parameters​

NameType
Textends RawVariant
Scopeextends string

Parameters​

NameType
scopeScope
vT

Returns​

ScopedVariant<T, Scope>

Defined in​

variant.ts:85


sequence​

â–¸ sequence<T, O>(module, order): Sequence<Pick<T, SequenceInputType<O, "type">>, O, "type", Pick<Pick<T, SequenceInputType<O, "type">>, SequenceInputType<O, "type">>>

Create a sequence based on a variant.

Type parameters​

NameType
Textends VariantModule<"type">
Oextends SequenceInput<"type", string>

Parameters​

NameTypeDescription
moduleTthe variant definition.
orderO[]the list of string literal types or variation creators.

Returns​

Sequence<Pick<T, SequenceInputType<O, "type">>, O, "type", Pick<Pick<T, SequenceInputType<O, "type">>, SequenceInputType<O, "type">>>

Defined in​

remote.ts:122

â–¸ sequence<O>(order): Sequence<VMFromVC<CreatorFromSeqInput<O, "type">>, O, "type", Pick<VMFromVC<CreatorFromSeqInput<O, "type">>, SequenceInputType<O, "type">>>

Create a sequenced variant.

Type parameters​

NameType
Oextends CreativeSequenceInput<"type", string>

Parameters​

NameTypeDescription
orderO[]the list of literal types or variation creators. Also the variant definition a la variantList.

Returns​

Sequence<VMFromVC<CreatorFromSeqInput<O, "type">>, O, "type", Pick<VMFromVC<CreatorFromSeqInput<O, "type">>, SequenceInputType<O, "type">>>

Defined in​

remote.ts:130


typeCatalog​

â–¸ typeCatalog<T>(variant): Identity<TypeCatalog<T>>

Create an a string enum-like object containing the type literals of a variant.

tutorial

ts
const Animal = variant({...}); // cat, dog, snake
const animalType = typeCatalog(Animal);
// animalType: {cat: 'cat', dog: 'dog', snake: 'snake'};
ts
const Animal = variant({...}); // cat, dog, snake
const animalType = typeCatalog(Animal);
// animalType: {cat: 'cat', dog: 'dog', snake: 'snake'};

Type parameters​

NameTypeDescription
Textends VariantModule<string>the variant template, an object containing variant creators.

Parameters​

NameTypeDescription
variantTthe definition of the variant in question.

Returns​

Identity<TypeCatalog<T>>

an object {[T: string]: T}

Defined in​

typeCatalog.ts:24


typeMap​

â–¸ typeMap<T>(variant): Identity<TypeMap<T>>

Create a mapping object containing the friendly names of a variant's forms and the type literals they correspond to.

tutorial

In the trivial case where each property label of a variant is exactly the type it generates, this is equivalent to typeCatalog

ts
const Animal = variant({...}); // cat, dog, snake
const animalType = typeMap(Animal);
// animalType: {cat: 'cat', dog: 'dog', snake: 'snake'};
ts
const Animal = variant({...}); // cat, dog, snake
const animalType = typeMap(Animal);
// animalType: {cat: 'cat', dog: 'dog', snake: 'snake'};

However, typeMap shines when differences come into play.

ts
const Animal = scopedVariant('@animal', {...}); // cat, dog, snake
const animalType = typeMap(Animal);
// animalType: {cat: '@animal/cat', dog: '@animal/dog', snake: '@animal/snake'};
ts
const Animal = scopedVariant('@animal', {...}); // cat, dog, snake
const animalType = typeMap(Animal);
// animalType: {cat: '@animal/cat', dog: '@animal/dog', snake: '@animal/snake'};

Type parameters​

NameTypeDescription
Textends VariantModule<string>the variant template, an object containing variant creators.

Parameters​

NameTypeDescription
variantTthe definition of the variant in question.

Returns​

Identity<TypeMap<T>>

Defined in​

typeCatalog.ts:55


typed​

â–¸ typed<T>(variant): VoidEmpty<ExactDefinition<T, "type">>

Enforce a variant following a pre-defined type.

example

type Option =
| Variant<'Some', {payload: any}>
| Variant<'None'>
;
const Option = variant(typed<Option>({
Some: pass,
None: pass,
}))
// `pass` is just the identity function. Any function `(input: T) => T` is valid.
type Option =
| Variant<'Some', {payload: any}>
| Variant<'None'>
;
const Option = variant(typed<Option>({
Some: pass,
None: pass,
}))
// `pass` is just the identity function. Any function `(input: T) => T` is valid.

Type parameters​

NameType
Textends Record<"type", string>

Parameters​

NameTypeDescription
variantExactDefinition<T, "type">implementation of the underlying functions.

Returns​

VoidEmpty<ExactDefinition<T, "type">>

the implementation passed in.

Defined in​

typed.ts:47

â–¸ typed<T>(factory): VoidEmpty<ExactDefinition<T, "type">>

Enforce a variant following a pre-defined type.

Receive the pass function as a parameter.

example

type Option =
| Variant<'Some', {payload: any}>
| Variant<'None'>
;
const Option = variant(typed<Option>(_ => ({
Some: _,
None: _,
})));
// `_` is just the identity function. Any function `(input: T) => T` is valid.
type Option =
| Variant<'Some', {payload: any}>
| Variant<'None'>
;
const Option = variant(typed<Option>(_ => ({
Some: _,
None: _,
})));
// `_` is just the identity function. Any function `(input: T) => T` is valid.

Type parameters​

NameType
Textends Record<"type", string>

Parameters​

NameTypeDescription
factory(_: <T>(x: T) => T) => ExactDefinition<T, "type">factory function implementation of the underlying functions. Receives pass as the only parameter.

Returns​

VoidEmpty<ExactDefinition<T, "type">>

the implementation passed in.

Defined in​

typed.ts:70


types​

â–¸ types<T>(content): Identity<TypesOf<T>>[]

Get the list of types from a variant.

Type parameters​

NameTypeDescription
Textends VariantModule<"type">target discriminated union

Parameters​

NameTypeDescription
contentTsome variant definition.

Returns​

Identity<TypesOf<T>>[]

list of string literal types.

Defined in​

types.ts:11

â–¸ types<C>(content): C["output"][``"type"``][]

Get the list of types from a list of variant creators.

Type parameters​

NameType
Cextends VariantCreator<string, Func, "type">

Parameters​

NameTypeDescription
contentC[]list of variant creators.

Returns​

C["output"][``"type"``][]

list of string literal types.

Defined in​

types.ts:18

â–¸ types<T>(content): T["type"][]

Get the list of types from the instances of a variant.

Type parameters​

NameTypeDescription
Textends Record<"type", string>target discriminated union

Parameters​

NameTypeDescription
contentT[]list of instances.

Returns​

T["type"][]

list of string literal types.

Defined in​

types.ts:25


unpack​

â–¸ Const unpack<T>(x): T

Extract the payload element from the object and return it.

example

match(object, {
...
case: unpack,
...
})
match(object, {
...
case: unpack,
...
})

Type parameters​

Name
T

Parameters​

NameType
xObject
x.payloadT

Returns​

T

Defined in​

match.tools.ts:22


variant​

â–¸ variant<VM>(template): Identity<GenericVariantRecord<VM, "type">>

Create a generic variant from some template. Use with onTerms().

tutorial

To create the classic Option<T> type (a.k.a. Maybe<T>)

ts
const Option = variant(onTerms(({T}) => ({
Some: payload(T),
None: {},
})));
type Option<T, TType extends TypeNames<typeof Option> = undefined>
= GVariantOf<typeof Option, TType, {T: T}>;
ts
const Option = variant(onTerms(({T}) => ({
Some: payload(T),
None: {},
})));
type Option<T, TType extends TypeNames<typeof Option> = undefined>
= GVariantOf<typeof Option, TType, {T: T}>;

Note the use of GVariantOf instead of VariantOf.

Type parameters​

NameType
VMextends RawVariant

Parameters​

NameTypeDescription
templateGenericTemplate<VM>a call to onTerms with some element.

Returns​

Identity<GenericVariantRecord<VM, "type">>

Defined in​

variant.ts:165

â–¸ variant<VM>(template): Identity<VariantRecord<VM, "type">>

Create a variant from some template.

example

ts
const Action = variant({
AddTodo: fields<{message: string}>(),
Reload: {},
});
// Pair with `variation` to override the type returned by the creator function
// while still using a friendly name. For example,
const Action = variant({
AddTodo: variation('TODO:AddTodo', fields<{message: string}>()),
Reload: variation('TODO:Reload'),
});
ts
const Action = variant({
AddTodo: fields<{message: string}>(),
Reload: {},
});
// Pair with `variation` to override the type returned by the creator function
// while still using a friendly name. For example,
const Action = variant({
AddTodo: variation('TODO:AddTodo', fields<{message: string}>()),
Reload: variation('TODO:Reload'),
});

Type parameters​

NameType
VMextends RawVariant

Parameters​

NameTypeDescription
templateVMan object where each property represents a possible variation. The key is the string literal used as the type and the value is a function that handles the creation logic for that type.

Returns​

Identity<VariantRecord<VM, "type">>

a variant module.

Defined in​

variant.ts:189

â–¸ variant<T>(template): Identity<VMFromVC<CreatorFromListType<T, "type">>>

Create a variant from a list of elements. Each element may be a string or a VariantCreator.

tutorial

The simplest use involves purely strings.

ts
const Suit = variant(['Spades', 'Hearts', 'Clubs', 'Diamonds']);
ts
const Suit = variant(['Spades', 'Hearts', 'Clubs', 'Diamonds']);

It is possible to use VariantCreators as well. Generate through variation().

ts
const Shape = variant([
variation('circle', fields<{center: [number, number], radius: number}>()),
variation('rectangle', fields<{center: [number, number], length: number, width: number}>()),
]);
ts
const Shape = variant([
variation('circle', fields<{center: [number, number], radius: number}>()),
variation('rectangle', fields<{center: [number, number], length: number, width: number}>()),
]);

Feel free to mix the approaches as necessary.

ts
const DebugAction = variant([
variation('LoadState', payload<RootState>()),
'ResetState',
'ToggleDebugMode',
]);
ts
const DebugAction = variant([
variation('LoadState', payload<RootState>()),
'ResetState',
'ToggleDebugMode',
]);

Type parameters​

NameType
Textends ValidListType

Parameters​

NameTypeDescription
templateT[]A list of string literals or calls to variation()

Returns​

Identity<VMFromVC<CreatorFromListType<T, "type">>>

a variant module.

Defined in​

variant.ts:222


variantCosmos​

â–¸ variantCosmos<K>(config): VariantCosmos<K>

Generate a series of functions to work off a given key.

Type parameters​

NameTypeDescription
Kextends stringdiscriminant as string literal.

Parameters​

NameTypeDescription
configVariantCosmosConfig<K>the key to use.

Returns​

VariantCosmos<K>

VariantCosmos<K>

Defined in​

cosmos.ts:43


variantList​

â–¸ variantList<T>(template): Identity<VMFromVC<CreatorFromListType<T, "type">>>

Create a variant from a list of elements. Each element may be a string or a VariantCreator.

tutorial

The simplest use involves purely strings.

ts
const Suit = variant(['Spades', 'Hearts', 'Clubs', 'Diamonds']);
ts
const Suit = variant(['Spades', 'Hearts', 'Clubs', 'Diamonds']);

It is possible to use VariantCreators as well. Generate through variation().

ts
const Shape = variant([
variation('circle', fields<{center: [number, number], radius: number}>()),
variation('rectangle', fields<{center: [number, number], length: number, width: number}>()),
]);
ts
const Shape = variant([
variation('circle', fields<{center: [number, number], radius: number}>()),
variation('rectangle', fields<{center: [number, number], length: number, width: number}>()),
]);

Feel free to mix the approaches as necessary.

ts
const DebugAction = variant([
variation('LoadState', payload<RootState>()),
'ResetState',
'ToggleDebugMode',
]);
ts
const DebugAction = variant([
variation('LoadState', payload<RootState>()),
'ResetState',
'ToggleDebugMode',
]);

Type parameters​

NameType
Textends ValidListType

Parameters​

NameTypeDescription
templateT[]A list of string literals or calls to variation()

Returns​

Identity<VMFromVC<CreatorFromListType<T, "type">>>

a variant module.

Defined in​

variant.ts:121


variantModule​

â–¸ variantModule<VM>(template): Identity<VariantRecord<VM, "type">>

Create a variant from some template.

example

ts
const Action = variant({
AddTodo: fields<{message: string}>(),
Reload: {},
});
// Pair with `variation` to override the type returned by the creator function
// while still using a friendly name. For example,
const Action = variant({
AddTodo: variation('TODO:AddTodo', fields<{message: string}>()),
Reload: variation('TODO:Reload'),
});
ts
const Action = variant({
AddTodo: fields<{message: string}>(),
Reload: {},
});
// Pair with `variation` to override the type returned by the creator function
// while still using a friendly name. For example,
const Action = variant({
AddTodo: variation('TODO:AddTodo', fields<{message: string}>()),
Reload: variation('TODO:Reload'),
});

Type parameters​

NameType
VMextends RawVariant

Parameters​

NameTypeDescription
templateVMan object where each property represents a possible variation. The key is the string literal used as the type and the value is a function that handles the creation logic for that shape. This may be {} or nil for an empty-bodied variant ({type: 'someType'}).

Returns​

Identity<VariantRecord<VM, "type">>

a variant module.

Defined in​

variant.ts:146


variation​

â–¸ variation<T, F>(type, creator?): VariantCreator<T, F extends VariantCreator<string, VF, "type"> ? VF : F, "type">

Specify a variation of a variant. One variant will have many variations.

tutorial Use directly, use as an element of a list for a variant, or use to provide a more specific underlying type.

  1. Use directly
    ts
    const snake = variation('snake', (name: string, pattern = 'string') => ({name, pattern}));
    ts
    const snake = variation('snake', (name: string, pattern = 'string') => ({name, pattern}));
  2. In variant list
    ts
    const Animal = variant([
    ...
    variation('snake', (name: string, pattern = 'striped') => ({name, pattern}));
    ]);
    ts
    const Animal = variant([
    ...
    variation('snake', (name: string, pattern = 'striped') => ({name, pattern}));
    ]);
  3. In variant object
    ts
    const Animal = variant({
    ...,
    snake: variation('ANIMAL_SNAKE', (name: string, pattern = 'striped') => ({name, pattern})),
    });
    ts
    const Animal = variant({
    ...,
    snake: variation('ANIMAL_SNAKE', (name: string, pattern = 'striped') => ({name, pattern})),
    });

Type parameters​

NameType
Textends string
Fextends Func = () => {}

Parameters​

NameTypeDescription
typeTthe string literal used as the distinguishing type.
creator?Fa function that acts as the body of the constructor.

Returns​

VariantCreator<T, F extends VariantCreator<string, VF, "type"> ? VF : F, "type">

a variation creator a.k.a. a tag construtor.

Defined in​

variant.ts:252


withFallback​

â–¸ withFallback<T, H, F>(handler, fallback): (input: T) => ExplicitHandler<H, F, T["type"]>

Resolve the match but account for edge cases.

Type parameters​

NameType
Textends Record<"type", string>
Hextends Handler<T, "type">
Fextends (instance: T) => any

Parameters​

NameType
handlerH
fallbackF

Returns​

fn

â–¸ (input): ExplicitHandler<H, F, T["type"]>

Resolve the match but account for edge cases.

Parameters​
NameType
inputT
Returns​

ExplicitHandler<H, F, T["type"]>

Defined in​

match.ts:91