Unionize
Define unions via records for great good!
Installation
yarn add unionize
Example
Provide unionize
with a mapping of tags to value types:
; ;
Extract the inferred tagged union:
;
The inferred type is:
We can also optionally provide tag and/or value property names:
;
Now the inferred type would be:
;
which is now FSA compliant.
Note that when the tag property is omitted, "tag"
will be used as the tag property. But if the value tag name is omitted, the generated sum type does not use a default "value"
property -- Instead, it intersects the value type with { [tagProp]: tag }
.
While this is convenient when dealing with value types which are objects (No need to access the value through a .value
accessor), it should be obvious that the value type can only be an object type if value tag is omitted.
So something like ofType<'SHOW_ALL' | 'SHOW_ACTIVE' | 'SHOW_COMPLETED'>
is only legal as a value type when a value
property name is provided:
The above fails with the error
Type '"SHOW_ALL" | "SHOW_ACTIVE" | "SHOW_COMPLETED"' is not assignable to type '{ [tag: string]: any; }'.
Type '"SHOW_ALL"' is not assignable to type '{ [tag: string]: any; }'.
Having done that, you now have at your disposal:
Element factories
store.dispatchActions.ADD_TODO;store.dispatchActions.SET_VISIBILITY_FILTER'SHOW_COMPLETED';store.dispatchActions.CLEAR_TODOS; // no argument required if value type is {}
Match expressions
;
action
can be omitted; in that case the result of match is a function:
; ;; // id === 'c819bbc1'
Type guards
.filterActions.is.ADD_TODO // The appropriately narrowed type of the resulting observable is inferred... .mergeMapconsole.logpayload.text;
Type casts
; // throws if someAction is not an ADD_TODO
Transform expressions
transform
is a shorthand alternative to match
for when you are converting from the union type to itself, and only want to handle a subset of the cases, leaving the rest unchanged:
; ;; ;; //didn't match. so dimmed === off; // can accept an object right away;
Breaking changes from 1.0.1
config object
Now unionize
accepts an optional config object instead of two additional arguments.
// beforeunionize, 'myTag', 'myPayloadProp';unionize, 'myTag'; // afterunionize, ;unionize, ;unionize, ; // <-- previously not possible
match
Whereas previously match
was always curried, now it can alternatively accept the object to match as a first argument. Additionally, the default case is now expressed as just another property in the cases object.
// beforeLight.match,'is off'light; // afterLight.matchlight;Light.matchlight, ;