sachinraja / zod-to-ts

generate TypeScript types from your Zod schema

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

FEAT: callback when he treats a type

mathcovax opened this issue · comments

I use this library to generate my front typing. But I encounter a problem with certain specific cases.

If my back returns an object with dates like this:

zod.object({
    firstname: zod.string(),
    dateOfBirth: zod.date(),
});

The generated type will be the following :

{
    firstname: string;
    dateOfBirth: Date;
}

A correct typing for the out of the back but wrong for the front, the real type that the front obtains is the following :

{
    firstname: string;
    dateOfBirth: string; // containe Date in this string
}

(Same problem for typing back entries)

Proposed solution :

zodToTs(
    zodSchema, 
    identifier, 
    [
        {
            type: ZodDate,
            callback: (zodDate) => {
                if(zodDate.def.coerce){
                    return zod.string() // replace a current ZodDate meets to ZodString
                }
                return zodDate
            }
        },
    ]
)

The operation would be simple, just before processing a type we look in the list if it has a match and if so launches the callback. the object returned from the callback will be the one that will be processed by the converter.

Thank you for your work. 😄