Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does typescript give an error when using a constant for an enum type?

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>>;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading