Question:
How to fix wrong type inference when using Zod?

Problem

In this validation schema, if the validation passes, the type of email will always be a string. However, for some reason typescript is telling me that the email either returns a string or false. I do not see any possibility that the email could ever return false, am I missing something?


To elaborate: When I use z.string().email(), I am guaranteeing that the outcome is indeed a valid email, otherwise the validation will fail and the value will not be passed to the transform > normalizeEmail part. So the final result must indeed be a string.


import { z } from "zod";

import validator from "validator";


const email = (maxChar: number) =>

  z

    .string()

    .max(maxChar)

    .email().transform((value) => validator.normalizeEmail(value))

    ;


Solution

validator.normalizeEmail returns false if the email is not valid (which is a strange design choice if you ask me). Since you are already checking if it is a valid email using Zod, I would opt for an >assertion:


const email = (maxChar: number) =>

  z

    .string()

    .max(maxChar)

    .email().transform((value) => validator.normalizeEmail(value) as string)

    ;


>Playground


Suggested blogs:

>Why Typescript does not allow a union type in an array?

>Narrow SomeType vs SomeType[]

>Create a function that convert a dynamic Json to a formula in Typescript

>How to destroy a custom object within the use Effect hook in TypeScript?

>How to type the values of an object into a spreadsheet in TypeScript?

>Type key of record in a self-referential manner in TypeScript?

>How to get the last cell with data for a given column in TypeScript?

>Ignore requests by interceptors based on request content in TypeScript?

>Create data with Typescript Sequelize model without passing in an id?

>How to delete duplicate names from Array in Typescript?


Nisha Patel

Nisha Patel

Submit
0 Answers