Skip to content

Strict enums from typescript types #3549

Answered by mdoury-oef
wcastand asked this question in Q&A
Discussion options

You must be logged in to vote

The UnionToTuple type from type-fest cat be used to ensure the zod enum type matches the GraphQL type from gql.tada.

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:

 Argument of type '["IMMEDIATE", "ONCE", "DAILY", "WEEKL…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@wcastand
Comment options

Answer selected by wcastand
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants