Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

typescript - io-ts : use TypeOf with DateFromISOString

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?

question from:https://stackoverflow.com/questions/66065543/io-ts-use-typeof-with-datefromisostring

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...