0

I have some objects where I want to change the Codec of one Property. Fort example I have a struct with a date field. Depending on 3rd system apis sometime the input value comes in form of a timestamp, sometimes in form of an ISO string. Is it possible without redeclaring everything else?

import * as COD from "io-ts/Codec";

const TimestampDateCodec: COD.Codec<unknown, number, Date> = {};
const IsoStringDateCodec: COD.Codec<unknown, string, Date> = {};

const current = COD.struct({
  id: COD.string,
  // a lot of other props...
  someDate: TimestampDateCodec, // change this to IsoStringDateCodec without redefining the whole struct
});


florian norbert bepunkt
  • 2,099
  • 1
  • 21
  • 32

1 Answers1

0

No, it is not possible. The recommended way to achieve this is as follows:

const base = {
  id: COD.string,
  // a lot of other props...
}

const OneVersion = COD.struct({
  ...base,
  someDate: TimestampDateCodec,
})

const AnotherVersion = COD.struct({
  ...base,
  someDate: IsoStringDateCodec,
})

Or, alternatively,

const base = COD.struct({
  id: COD.string,
  // a lot of other props...
})

const OneVersion = COD.union([base, COD.struct({
  someDate: TimestampDateCodec,
})])

const AnotherVersion = COD.union([base, COD.struct({
  someDate: IsoStringDateCodec,
})])

The latter is appealing if you like thinking in terms of sum types, but I think the former will result in an easier-to-read type in your IDE. I often do the latter and regret it because my IDE will tell me some time is of form { ...base } & { ...someDate... } & ... dependent on how many things I've union'ed.

user1713450
  • 1,307
  • 7
  • 18