Search code examples
javascriptarraystypescriptzod

Typescript - Check if mapped array contains a string[] for zod schema validation


This is for zod schema validation but it probably has a simple Javascript answer. My issue is that val (what the user passes in) is of type string[] but when I use val inside of .includes(val), it is just of type string.

For context, this is for a checkbox selection which allows the user to select more than one option (hence val is of type string[]). I want my validation to just check if at least one field was selected.

export const userInfoSchema = object({
  professions: z
    .string()
    .array()
    .refine((val) => fieldsOfEng.map((field) => field.name).includes(val))
  })

The error I'm getting is a red squiggly under the val in the .includes(val) part:

Argument of type 'string[]' is not assignable to parameter of type 'string'.ts(2345)

Solution

  • z.string().array() produces the type z.ZodArray<z.ZodString> and that's what the val in refine refers to. It's an array of profession-strings. So you have to check agains each of them

    export const userInfoSchema = z.object({
      professions: z
        .string()
        .array()
        .refine((val) => val.some(profession => 
          fieldsOfEng
            .map((field) => field.name)
            .includes(profession)))
    })
    

    Otherwise, if you feel confident that the checkbox values provided all come from fieldsOfEng (say, you have a separate test for that), you could just check if the array is empty

    const professionsSchema = z.array(z.string()).nonempty()
    
    const userSchema = z.object({
      professions: professionsSchema
    })
    

    codeSandbox link: https://codesandbox.io/s/zod-array-wei88r