turkerdev / fastify-type-provider-zod

MIT License
411 stars 25 forks source link

hasZodFastifySchemaValidationErrors does not narrow down the error types #124

Open Ram-Ratan opened 1 month ago

Ram-Ratan commented 1 month ago

I was trying to write a function to format the error I got from fastify schema validator. Once I check for hasZodFastifySchemaValidationErrors typescript does not allow me to access error.parmas.issue.

const transformError = (error: FastifyError) => {
    if (hasZodFastifySchemaValidationErrors(error)) {
        const validation = error.validation; //types:  FastifySchemaValidationError[] & ZodFastifySchemaValidationError[]
        return validation.map(
            (error, ind) => `Error #${ind + 1}: Code: ${error.params.issue.code} ~ Name: ${error.params.issue.path} ~ Message: ${error.params.issue.message} `
        );
    }
    return error;
};
//~~~~ 'error.params.issue' is of type 'unknown'
//~~~~ 'error.params.issue' is of type 'unknown'
//~~~~ 'error.params.issue' is of type 'unknown'

I need to do type assertion to make this work. By the way I am new to fastify and zod please me know if I am doing some thing wrong. Thanks.