-
Notifications
You must be signed in to change notification settings - Fork 319
Closed
Labels
experimentalsomething related to the experimental featuressomething related to the experimental features
Description
I have two doubts:
-
Difference between
Decoder.unionandDecoder.sum- Is
Decoder.sumoptimized and should be used whenever possible?
- Is
-
Decoder.sumis not typesafe- In second argument of
sum,keyofobjectcan be different than the correspondingvalue - Fails at runtime, shown in following example
- In second argument of
const CircleD = D.type({
kind: D.literal('Circle'),
radius: D.number
})
const SquareD = D.type({
kind: D.literal('Square'),
x: D.number
})
// note here, key 'Circle1' is not valid but does not issue compile time error
const ShapeD = D.sum('kind')({
Circle1: CircleD,
Square: SquareD
})
// fails at runtime
ShapeD.decode({
kind: 'Circle',
radius: 10
})Above issue can be resolved if signature of sum is changed to following:
import * as D from 'io-ts/lib/Decoder'
const sum = <T extends string>(tag: T) => <A>(
members: { [K in keyof A]: Decoder<A[K] extends { [Key in T]: K } ? A[K] : never> }
): Decoder<A[keyof A]> => D.sum(tag)(members)
// fails to compile
sum('kind')({
Circle1: CircleD,
Square: SquareD
})Happy to submit PR if this make sense.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
experimentalsomething related to the experimental featuressomething related to the experimental features