colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
33.09k stars 1.15k forks source link

Proper inference of a string to typeof keyof Object #3685

Closed QuentinLemCode closed 3 weeks ago

QuentinLemCode commented 1 month ago

Hello,

I'm starting using Zod and I haven't figure out how to proper infer string union type from key of an object without using a type guard.

Here is a sample Zod schema :

const obj = z.object({
  foo: z.optional(z.boolean()),
  bar: z.optional(z.boolean()),
})

And then I have a function that take a string in parameter and I would like to validate it's a key of the object and infer it.

function checkKey(key: string) {
  if (key in obj.keyof()) {
    // key is still of type 'string', should be 'foo' | 'bar'
}

Example stackblitz : https://stackblitz.com/edit/stackblitz-starters-qfu3yi?file=index.ts

Is this something possible without using type guard right now ? Maybe a potential feature ?

sunnylost commented 3 weeks ago

obj.keyof() returns a schema, you can't use it as a value, do something like this:

function checkKey(key: string) {
    const result = obj.keyof().safeParse(key)

    if(result.success) {
        needCorrectType(result.data, {})
    }
}
QuentinLemCode commented 3 weeks ago

obj.keyof() returns a schema, you can't use it as a value, do something like this:

function checkKey(key: string) {
    const result = obj.keyof().safeParse(key)

    if(result.success) {
        needCorrectType(result.data, {})
    }
}

Thank you very much 🙏