I am trying to create union codec from type codec in io-ts. What I am trying to achieve is basically transforming from:
import * as t from 'io-ts'
const FilterTypeC = t.type({
POTATO: t.literal('POTATO'),
CABBAGE: t.literal('CABBAGE'),
BANANA: t.literal('BANANA'),
TOMATO: t.literal('TOMATO'),
});
into:
const FilterTypeUnionC = t.union([t.literal('POTATO'), t.literal('CABBAGE'), t.literal('BANANA'), t.literal('TOMATO')])
Is there some kind way for that in io-ts? I tried adapating similar typescript example but without success.
If I understand correctly what you're looking for, you have a
TypeC
codec already, and are trying to create a new codec that checks for the union of the possible values of that base codec? The TypeScript type you're looking for would be something like this?where the codec would decode the values of the given interface.
I don't think that
io-ts
supports this out of the box, but I was able to write a quick function to create a codec given aTypeC
.This should do the trick, but I would warn slightly that this is relying on special meta data present on the
t.TypeC
class so this won't work with other codecs even if theA
type is a record / interface.