sinclairzx81 / typebox

Json Schema Type Builder with Static Type Resolution for TypeScript
Other
4.85k stars 155 forks source link

Unable to assign a default Date #531

Closed jtlapp closed 1 year ago

jtlapp commented 1 year ago

This could be just me misunderstanding something, but so far I have not found a way to assign a default Date.

The following yields a classless object {} as the date:

Type.Date({ default: new Date() }),

And the following yields a string as the date:

Type.Date({ default: new Date().toISOString() }),
jtlapp commented 1 year ago

I think I know why. TypeBox must produce valid JSON, and JSON can't represent instances of Date.

So if I want default dates, I'll need to use the ISO string and parse it into a date.

jtlapp commented 1 year ago

I'll close this assuming my conclusion is correct.

sinclairzx81 commented 1 year ago

@jtlapp Hi!

I think I know why. TypeBox must produce valid JSON, and JSON can't represent instances of Date. ... So if I want default dates, I'll need to use the ISO string and parse it into a date.

There's actually some changes happening in the next revision of the library to draw a stronger distinction between Json serializable values, and JavaScript non-serializable values. The StandardTypeBuilder is being renamed to JsonTypeBuilder and the ExtendedTypeBuilder is being renamed to JavaScriptTypeBuilder (with perhaps more focus put on trying to define a common set of serializable schematics for JavaScript constructs). Doc comments are also being updated to reflect the change (as many developers do trip over TypeBox Date types without realizing Json has no way to encode them (other than timestamps or iso strings)

You can read up on the next revision here https://github.com/sinclairzx81/typebox/pull/525 (there's actually some big changes in this revision across the board), including some functionality for IO encode/decode (relevant to convert from json encoded dates to JavaScript Date objects)

Cheers

jtlapp commented 1 year ago

Excellent. There may be some overlap in what we're doing. I'm currently working on a utility for parsing form and query parameter data according to a TypeBox schema. Here's the work in progress.

This is to support a TypeBox adaptation of sveltekit-superforms, which I'm also working on.