Home > Software engineering >  Why does typescript give an error when using a constant for an enum type?
Why does typescript give an error when using a constant for an enum type?

Time:05-30

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

CodePudding user response:

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.

  • Related