ITADN

How to handle ISO string dates?

#1546Closedromeerez 创建于 2026-03-16
R
romeerezcommented
What's the proper way to parse ISO strings with typebox? For clarification, to do what zod does with `z.iso.date()`: ```ts const date = z.iso.date(); date.parse("2020-01-01"); ``` Here is what I tried and it works: ```ts const UnsafeDate = Type.Unsafe<Date>({type: 'date'}); const TypeDate = Type.Refine(UnsafeDate, (value) => value instanceof Date && !isNaN(value.getTime()), 'invalid date'); const TypeIsoDate = Type.Codec(TypeDate).Decode((value) => value.toISOString()).Encode((value) => new Date(value)); const parsed: Date = Value.Encode(TypeIsoDate, '2020-01-01'); console.log(parsed); ``` But I think that `Encode`/`Decode` semantics is broken by this. - I understand `Encode` as "serialize for transferring" - `Decode` is a "deserialize", "parse", i.e. transform raw input to the app data structure But if I swap `Decode` and `Encode` places in my custom `TypeIsoDate`, is `Decode` a proper place for a validation, how would I throw "invalid date" error in a way for typebox to handle it?
关闭于 2026-03-17 2 条评论