Skip to content

feat: Bind return type of a procedure to the input type of the output schema #6978

Open

Description

@felixnorden

Describe the feature you'd like to request

With Zod V4.1 introducing Codecs, we get a more "lightweight" option for encoding and decoding data (e.g., instead of using Transformers). However, the current implementation of the type inference binds the returned type of a procedure to the output type of the parse function, rather than the input.

This restricts the output schema in that it can't apply transformations and is only capable of validations 1:1.

For example, if I have a schema with a codec stringToBigInt (as per the docs) and would look to do something like the code below, I'll face type inference issues stating that Type string is not assignable to bigint, even though the underlying schema and runtime types would align.

function encode<TSchema extends z.ZodType>(schema: TSchema) {
  return (value: unknown) => schema.encode(value as z.output<TSchema>) // as-coercion needed due to the input type of the `ParseFn` being `unknown`
}

//...
procedure.output(encode(z.object({x: stringToBigInt}))).query(() => ({x: 0n}))

Describe the solution you'd like to see

To get this working, it seems like what's needed is to enable chained middlewares to align output types of prior middlewares as input types to the successors.

The MiddlewareOKResult could have a type parameter which defaults to unknown which then is set in createOutputMiddleware instead of leaving the outputMiddleware as an AnyMiddlewareFunction, which is used to narrow the type on the middleware output type.

From what I can see, the ParseFn type would also need an argument type parameter TInput (default to unknown), e.g.,

type ParseFn<TOutput, TInput = unknown> = (value: TInput) => Promise<TOutput> | TOutput

of which there are then some areas where types need to be updated to ensure it aligns well.

Describe alternate solutions

Right now, I have to do type coercions that I don't necessarily like to make this work. The solution is to do the following (using the initial example):

function encode<TSchema extends z.ZodType>(schema: TSchema) {
  return (value: unknown) => schema.encode(value as z.output<TSchema>) // as-coercion needed due to the input type of the `ParseFn` being `unknown`
}

//...
const schema = z.object({x: stringToBigInt})
procedure.output(encode(schema)).query(() => ({x: 0n}) as unknown as z.input<typeof schema>) // coerce to input type although it's the output shape to be encoded through the codec to be the input shape

Additional information

If I have missed any requirements and this is a useful feature for others, please let me know how I can assist.
If there are other ways of going about this in a more typesafe way, do let me know as well!

👨‍👧‍👦 Contributing

  • 🙋‍♂️ Yes, I'd be down to file a PR implementing this feature!

Activity

  1. added
    ✅ accepted-PRs-welcome
    on Oct 20, 2025
  2. KATT commented on Oct 20, 2025

    @KATT
    Member

    Not sure if I follow, but curious to see a PR :)

  3. felixnorden commented on Oct 20, 2025

    @felixnorden
    Author

    Not sure if I follow, but curious to see a PR :)

    Will see what I can do!
    To try and simplify: Zod Codecs act as bidirectional transforms and using schemas that have codecs in them mean that the input type (TInput) and the output type (TOutput) to the schema will differ and cause either type error or runtime errors.

    The returned value of a procedure is either of TInput or TOutput; if it's of TInput, the type check will fail as the value isn't matching the type TOutput. If it's instead of type TOutput, then there will be a runtime error as the schema will see that the value is not matching TInput and the validation will fail.

  4. Sourav12061999 commented on Nov 20, 2025

    @Sourav12061999

    Hi @felixnorden , if you don't mind could you please leave it to me, would love to work on it

  5. felixnorden commented on Nov 20, 2025

    @felixnorden
    Author

    Yeah feel free to if you want to pick it up, I've begun tinkering with it after work hours to help facilitate parts of our work, so if you want to bounce ideas, let me know @Sourav12061999

  6. lukeramsden commented on Dec 9, 2025

    @lukeramsden

    Most certainly not proposing to merge this code but here's some exploratory work I did in a Claude Code session - how does this line up with everyone's thoughts?

    lukeramsden#1

  7. bas0N commented on Dec 13, 2025

    @bas0N

    @felixnorden If no one has started on this yet, I can take it

  8. felixnorden commented on Dec 16, 2025

    @felixnorden
    Author

    @bas0N , I've held off as people above have wanted to take a stab at it, so feel free to do so yourself. Otherwise, I'll aim to get to this during the Holidays 🤝

  9. bas0N commented on Dec 23, 2025

    @bas0N

    @felixnorden pr is ready with the implementation you outlined

  10. KATT commented on Nov 2, 2026

    @KATT
    Member

    🤖 Passing the schema itself (not a function wrapping it) already does this in v11: the resolver returns the output schema's input type, the client gets its output type, and the transform runs on the server. A plain (value: unknown) => … parser has one type for both sides, which is why encode() hit the error.

    const bigintToString = z.codec(z.bigint(), z.string(), {
      decode: (value) => value.toString(),
      encode: (value) => BigInt(value),
    });
    
    t.procedure
      .output(z.object({ x: bigintToString }))
      .query(() => ({ x: 0n })); // the client gets { x: string }

    Reusing one codec both ways (.encode() on the output) isn't supported. As Nick said on #7073, a PR is welcome if userland tests show it's more typesafe than this. Docs: https://trpc.io/docs/server/validators#output-validators.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    ✅ accepted-PRs-welcome

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions