You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
For working with tagged unions, I'm a fan of unionize. Below I outline the pros and cons of working with tagged unions in both io-ts and unionize.
However, for all of unionize's benefits over io-ts, the one big thing missing is validation, which of course io-ts aims to provide.
By outlining the pros/cons of both approaches, my hope is that we can find a way to improve io-ts so that we can have the best of both worlds: concise syntax and validation.
Do you have any thoughts on this?
io-ts
// Pros:// - `switch` can match multiple cases at once// Cons:// - Definition is verbose// - Tag is required during construction// - Renaming tags will not update all usages and the type definitionimport*astfrom'io-ts';// DefinitionconstFooRT=t.type({tag: t.literal('Foo'),foo: t.number});typeFoo=t.TypeOf<typeofFooRT>;constBarRT=t.type({tag: t.literal('Bar')});typeBar=t.TypeOf<typeofBarRT>;constBazRT=t.type({tag: t.literal('Baz')});typeBaz=t.TypeOf<typeofBazRT>;constModalRT=t.taggedUnion('tag',[FooRT,BarRT,BazRT]);typeModal=t.TypeOf<typeofModalRT>;// ConstructionModalRT.encode({tag: 'Foo',foo: 2});ModalRT.encode({tag: 'Foo',foo: 'foo'});// MatchingconstmatchModal=(modal: Modal)=>{switch(modal.tag){case'Foo':
returnmodal.foo;case'Bar':
case'Baz':
return2;}};
unionize
// Pros:// - Renaming tags will update all usages and the type definition// - Tag can be omitted during construction// - Definition is concise// Cons:// - Unlike `switch`, can't match multiple cases at onceimport{unionize,ofType}from'unionize';// DefinitionconstModal=unionize({Foo: ofType<{foo: number}>(),Bar: ofType<{}>(),Baz: ofType<{}>(),});typeModal=typeofModal._Union;// ConstructionModal.Foo({foo: 2});Modal.Foo({foo: 'foo'});// MatchingconstmatchModal=Modal.match({Foo: ({ foo })=>foo,Bar: ()=>2,Baz: ()=>2,});
The text was updated successfully, but these errors were encountered:
Related pelotom/unionize#41
For working with tagged unions, I'm a fan of unionize. Below I outline the pros and cons of working with tagged unions in both io-ts and unionize.
However, for all of unionize's benefits over io-ts, the one big thing missing is validation, which of course io-ts aims to provide.
By outlining the pros/cons of both approaches, my hope is that we can find a way to improve io-ts so that we can have the best of both worlds: concise syntax and validation.
Do you have any thoughts on this?
io-ts
unionize
The text was updated successfully, but these errors were encountered: