0

When I try to pass a conatant instead of in-place values ​​for the field below, I get a type error, but if I use an in-place value, everything works fine

import * as z from "zod";

const data = ["1", "2"];

// this way works fine
/*
  age: z.enum<any, [string, ...string[]]>(["1", "2"])
*/

const schema = z.object({
  name: z.number(),
  age: z.enum<any, [string, ...string[]]>(data) // error here
});

and here is how z.enum type look

declare function createZodEnum<U extends string, T extends Readonly<[U, ...U[]]>>(values: T): ZodEnum<Writeable<T>>;

1 Answer 1

1

Note that T extends Readonly<[U, ...U[]]>, it would require a type like ['foo', 'bar', /* etc */], but not Array<string>.

In your code,

const data = ["1", "2"];

is actually inferred as

const data: Array<string> = ["1", "2"];

You could either

const data = ["1", "2"] as const;

or as the way you've commented out.


Note how the README said

Alternatively, use as const to define your enum values as a tuple of strings. See the const assertion docs for details.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I have found already, but anyway thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.