JSDoc for schema and inferred type #841
-
Is there a way to attach JSDoc to the schema and inherit it with inferred types? export const UserSchema = z.object({
/** UTC ISO date time string */
createdAt: z.string(),
}); So this documentation would be visible in the tool tips. And after getting the type: export type User = z.infer<typeof User>; I would see this JSDoc there as well, so it could be taken by TypeDoc and appear in the generated documentation? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
I'm not sure that there is a way to do what you are asking for using JSdocs. However, you could do something like what I have below. Hopefully someone else will be able to chime in if this is possible with just JSdocs. /** UTC ISO date time string */
type ISODateString = `${number}-${number}-${number}T${number}:${number}:${number}Z`
function isIsoDate ( string: string ): string is ISODateString {
if ( !/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/.test( string ) ) return false
return new Date( string ).toISOString() === string
}
const isoDateString = z.string().refine( isIsoDate )
const UserSchema = z.object( { createdAt: isoDateString } )
type User = z.infer<typeof UserSchema>
type CreatedAt = User[ 'createdAt' ]
//-> CreatedAt = `${number}-${number}-${number}T${number}:${number}:${number}Z` Unfortunately, I'm not sure how to make Hope this helps. |
Beta Was this translation helpful? Give feedback.
-
After digging into this some more, I'm pretty sure that not being able to see the JSdoc after const UserSchema = z.object( {
/** UTC ISO date time string */
createdAt: z.string()
} )
typeof UserSchema.shape[ 'createdAt' ]
// when you hover over 'createdAt' then the popup shows the JSdoc
// (property) createdAt: z.ZodString
// UTC ISO date time string
type CreatedAt = typeof UserSchema.shape[ 'createdAt' ]
// but unfortunately, when you make a type alias, it loses the JSdoc
//-> CreatedAt = z.ZodString |
Beta Was this translation helpful? Give feedback.
After digging into this some more, I'm pretty sure that not being able to see the JSdoc after
z.infer
is a problem with typescript and I don't think there is anything Zod can do to fix that.