mojotech / mojotech/json-type-validation
Enum decoders are cumbersome and not intuitive
Nobody has claimed this yet.
- Dominant language
- TypeScript
- Stars
- 154
- Forks
- 14
- PR merge metrics
- No merged PRs in 30d
Description
Given a TS enum
enum Directions { North, South, East, West }
We currently write the decoder as
const directionsDecoder: Decoder<Directions> = oneOf(
constant(Directions.North),
constant(Directions.South),
constant(Directions.East),
constant(Directions.West)
);
which isn't great.
It's worth noting that the most ideal syntax is not possible, since TS compiles out enums and hardcodes the enum values during compilation
const directionsDecoder = enumDecoder(Directions); // this doesn't work!
Something like this should be possible:
const enumDecoder = <E>(...enumValues: Array<E[keyof E]>): Decoder<E> =>
oneOf(...enumValues.map((v) => constant(v)));
const directionsDecoder = enumDecoder(
Directions.North, Directions.South, Directions.East, Directions.West
);
But no matter how I bash at the types I am unable to get the type checker to reconcile the relationship between the elements of the enum and the enum in total.
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Read the existing oneOf and constant decoder APIs first, then investigate how TypeScript infers the relationship between enum members and the enum type. Done means an enumDecoder-style helper can accept the listed enum values, return a Decoder, and preserve type checking for the proposed usage.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100