0

trying to validate and decode api response:

const Foo  = t.type({
    id: t.number,
    date: DateFromISOString,
  });

  type FooType = t.TypeOf<typeof Foo>;
  const jsonFoo: FooType = {"id": 1, date: "2021-02-05T11:13:22.520Z"};
  const resultFoo = Foo.decode(jsonFoo);

the problem is that type describes data property as a date while it's string in jsonFoo

Do I miss something there or I need 2 types for both incoming data and decoded object?

Anton
  • 1,898
  • 3
  • 18
  • 27
  • [DateFromISOString](https://gcanti.github.io/io-ts-types/modules/DateFromISOString.ts.html#datefromisostring) represents an instance of Date if I understand correctly. – Nishant Feb 05 '21 at 17:34

1 Answers1

2

You can simply use the 'union' function and merge the DateFromISOString and string types.

const Foo = t.type({
      id: t.number,
      date: t.union([DateFromISOString, t.string]),
    });

Another solution I found was this:

Build a Date instance from the string and then pass it to the string again using the 'toISOString' helper function.

const Foo = type({
      id: number,
      date: DateFromISOString,
    });

type FooType = TypeOf<typeof Foo>;
const jsonFoo: FooType = { id: 1, date: new Date("2021-02-05T11:13:22.520Z") };
const resultFoo = Foo.decode(jsonFoo);

const input = jsonFoo.date.toISOString();

assert.deepStrictEqual(input, right(jsonFoo.date)); // fails
assert.deepStrictEqual(DateFromISOString.decode(input), right(jsonFoo.date)); // success