zod: Can't generically compose + transform schema without type error

Say I want to do something like this:

https://tsplay.dev/mq9bjm

import { z } from 'zod'

async function stripOuter<TData extends z.ZodTypeAny>(schema: TData, url: string): Promise<TData> {
  const zStrippedResponse = z
    .object({
      topLevelKey: schema,
    })
    .transform(data => {
      return data.topLevelKey
      //     ^?
    })
  
  return fetch(url)
    .then(response => response.json())
    .then(data => zStrippedResponse.parse(data))
}

I get the following type error:

Property 'topLevelKey' does not exist on type '{ [k in keyof baseObjectOutputType<{ topLevelKey: TData; }>]: baseObjectOutputType<{ topLevelKey: TData; }>[k]; }'.

Is this something I should be able to do? Any pointers where I’m going wrong?

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Reactions: 1
  • Comments: 16 (9 by maintainers)

Most upvoted comments

@JacobWeisenburger canary releases don’t seem to be triggering, I think this should fix it? https://github.com/colinhacks/zod/pull/2148

Bug confirmed

function foo<Schema extends z.AnyZodObject> ( schema: Schema ) {
    return z.object( { bar: schema } ).transform( x => x.bar )
    //                                                   ^^^
    // Property 'bar' does not exist on type
    // '{ [k in keyof baseObjectOutputType<{ bar: Schema; }>]: baseObjectOutputType<{ bar: Schema; }>[k]; }'.
}