paarthenon / variant

Variant types in TypeScript
https://paarthenon.github.io/variant
Mozilla Public License 2.0
184 stars 3 forks source link

Scoped Variants (/namespaces) #10

Closed paarthenon closed 3 years ago

paarthenon commented 3 years ago

As things are each variant is compared purely based on type value, which means there can be name conflicts if you set up multiple actions.


export const Action = {
    ...AppAction,
    ...RequestAction,
};

AppAction and RequestAction may both contain a LoadTodos action, which will cause a conflict if an action of RequestAction is checked to be isOfType(_____, AppAction) because it will wrongfully return true.

Scoped types (@action/TYPE) are the resolution to this, and TypeScript's 4.1 string templating features make this an ideal feature for this library.


I have already implemented a version of this, but there remains a discussion on which delimiter is most appropriate. Also to allow for users who have not yet updated, TypeScript 4.1-specific features will be released in variant 2.1+.

paarthenon commented 3 years ago

Implemented in 2.1.0-beta.0 available via variant@test

Requires TS 4.1

Use as

export const ScopedAnimal = scopedVariant('animal', {
   dog: fields<{...}>(),
   bird: {},
});

then to match

const func = (anim: ScopedAnimal) => match(descope(anim), {
    dog: constant(4),
    default: constant(5),
});
paarthenon commented 3 years ago

Documentation is now available here:

https://paarthenon.github.io/variant/docs/use/advanced-creation#scoped-variants

paarthenon commented 3 years ago

This will be released as part of variant 3.0 and is available now in variant@dev