Strict enums from typescript types #3549
-
my use case is, i use we use zod to define schema and validate our form, etc so i wanted to create an enum in zod that match and is validated by the enum from gql.tada. code look like this:
but in it's case i get no error from typescript while it should because zod enum is missing MONTHLY. I tried different lib and superstruct has
was wondering if zod had an equivalent to EDIT: |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The import { type UnionToTuple } from "type-fest"
import { type graphql } from "gql.tada"
import { z } from "zod"
type Scalar<TScalar extends Readonly<string>> = ReturnType<typeof graphql.scalar<TScalar>>
const FrequencySchema = z.enum<string, UnionToTuple<Scalar<"Frequency">>>(
["IMMEDIATE", "ONCE", "DAILY", "WEEKLY", "MONTHLY"]
) // ✅
const FrequencySchema = z.enum<string, UnionToTuple<Scalar<"Frequency">>>(
["IMMEDIATE", "ONCE", "DAILY", "WEEKLY"]
) // ❌ Error for missing members should look something like this:
Caveat: the array order needs to match the union order. |
Beta Was this translation helpful? Give feedback.
The
UnionToTuple
type from type-fest cat be used to ensure the zod enum type matches the GraphQL type fromgql.tada
.Error for missing members should look something like this: