Skip to content

bug: Invalid serialization of zod branded tuples #6500

Closed

Description

@davazp

Provide environment information

  System:
    OS: macOS 15.3.1
    CPU: (16) arm64 Apple M3 Max
    Memory: 17.81 GB / 48.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 18.16.0 - ~/.nvm/versions/node/v18.16.0/bin/node
    Yarn: 1.22.21 - ~/.nvm/versions/node/v18.16.0/bin/yarn
    npm: 9.5.1 - ~/.nvm/versions/node/v18.16.0/bin/npm
    pnpm: 8.14.3 - ~/.nvm/versions/node/v18.16.0/bin/pnpm
  Browsers:
    Chrome: 133.0.6943.55
    Safari: 18.3
  npmPackages:
    @trpc/client: 11.0.0-rc.741 => 11.0.0-rc.741+caed91ee7 
    @trpc/server: 11.0.0-rc.741 => 11.0.0-rc.741+caed91ee7 
    typescript: 5.7.3 => 5.7.3 

Describe the bug

The trpc client fails to infer the output type of a zod-serialized tuple.

For a procedure like this

export const Point = z
  .tuple([z.number(), z.number(), z.number()])
  .brand("Point");
export type Point = z.infer<typeof Point>;

export const appRouter = t.router({
  getPoint: t.procedure.query(async () => {
    return {
      point: [1, 2, 3] as Point,
    };
  }),
});
const result = await trpc.getPoint.query();  // has type
{
    point: SerializeTuple<[number, number, number] & BRAND<"Point">>;
}

This type isn't assignable to Point:

Type 'SerializeTuple<[number, number, number] & BRAND<"Point">>' is not assignable to type '[number, number, number] & BRAND<"Point">'.
  Type 'SerializeTuple<[number, number, number] & BRAND<"Point">>' is not assignable to type '[number, number, number]'.
    Types of property 'length' are incompatible.
      Type 'number' is not assignable to type '3'

Workaround

I can define a dummy transformer to make trpc bail out and not try to transform the types. Then I get the right type in the frontend.

Link to reproduction

https://github.com/davazp/trpc-bug-branded-tuples

To reproduce

https://github.com/davazp/trpc-bug-branded-tuples

Additional information

The SerializedTuple definition here

/** JSON serialize [tuples](https://www.typescriptlang.org/docs/handbook/2/objects.html#tuple-types) */
type SerializeTuple<T extends [unknown, ...unknown[]]> = {
  [K in keyof T]: T[K] extends NonJsonPrimitive ? null : Serialize<T[K]>;
};

The indexing here will treat this as an object

type T = Serialize<[1,2,3] & {__brand: void}>;
type T = {
    [x: number]: 1 | 3 | 2;
    0: 1;
    1: 2;
    2: 3;
    length: 1 | 3 | 2;
    toString: null;
    toLocaleString: null;
    pop: null;
    push: null;
    concat: null;
    join: null;
    reverse: null;
    shift: null;
    slice: null;
    sort: null;
    splice: null;
    ... 23 more ...;
    __brand: 1 | ... 1 more ... | 2;
}

Some typewizardy is needed. However, I guess this affects other type of branded types and other situations.

It would be simpler if, instead, trpc would just check that the output type is JSON compatible, giving an error otherwise, but returning the original type unmodified.

But sure, then procedures could not return Date for instance. I think it is fair, define a serializer if you want that? But it's a breaking change.

👨‍👧‍👦 Contributing

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

Activity

  1. davazp commented on Feb 15, 2025

    @davazp
    Author

    Also, unrelated, but I had to install @types/node for the inference in the client to work. Without it, or additional tsconfig setup, the output type was always inferred as a AsyncIterable. I could fill a separate issue for it.

  2. KATT commented on Feb 15, 2025

    @KATT
    Member
  3. davazp commented on Feb 15, 2025

    @davazp
    Author

    @KATT I have tried. But it only covers a basic use case of branded types. That's why I suggest the other approach. (Read below)

    For this one, I got pretty close with this change:

    type TupleKeys<T> = Extract<keyof T, `${number}`>;
    type TupleBrandedKeys<T> = Exclude<keyof T, keyof any[] | TupleKeys<T>>;
    
    /** JSON serialize [tuples](https://www.typescriptlang.org/docs/handbook/2/objects.html#tuple-types) */
    type SerializeTuple<T extends [unknown, ...unknown[]]> = {
      [K in TupleKeys<T>]: T[K] extends NonJsonPrimitive ? null : Serialize<T[K]>;
    } & {
      [K in TupleBrandedKeys<T>]: T[K];
    }

    It will produce

    type T = Serialize<[number, string, Date] & {__brand: void}>;
    =>
    type T = {
        0: number;
        1: string;
        2: string;
    } & {
        __brand: void;
    }

    This would be enough for simple branded tuple types like the one I reported it.

    However, branded types can be used in so many other situations. Over strings, numbers or even objets. How would we know what fields to serialize and what fields are used to create a brand?

    My suggested solution

    Instead of trying to be too clever trying to map Date to string, we could always just return the output type of the procedures. Like we do now if transformer is defined. The client always see the same type, untransformed, preserving branded types and any other type magic.

    What if a procedure returns {date: new Date()}? If we want to prevent this, we could have a type similar to

    type inferredOutputType<T> = T extends JSONCompatible? T: never
    type JSONCompatible =
      | JsonPrimitive
      | { [key: string]: JSONCompatible }
      | JSONCompatible[];
    
    type TestOk = inferredOutputType<[number, number, number] & { __brand: void }>;
    type TestFail = inferredOutputType<[number, Date, number] & { __brand: void }>; // never
    
    // Zod style branded types
    const BRAND = Symbol();
    type TestZodOk = inferredOutputType<[number, string, number] & { [BRAND]: true }>;
    type TestZodFail = inferredOutputType<[number, Date, number] & { [BRAND]: true }>; // never

    This way, procedures returning Date, Map and other basic types should fail. But we never, otherwise, transform types provided to the user for the client.

    Thoughts of this?

    I can keep using my workaround of defining transformer to opt-out of the current transformation, and being careful to not include Dates/Map/Sets (I am avoiding superjson, it is too slow for my current project).

    But I think for most people, the protection against Date/Map is enough. If they want Date to be mapped to a string they can do it in their procedure explicitly. And not transforming the types opens the door to use more advanced typing in applications.

  4. KATT commented on Feb 20, 2025

    @KATT
    Member

    For this one, I got pretty close with this change:

    Very close indeed! I had a stab at it in #6538 but it loses the brand - feel free to try to to make a PR with an improvement?

    What if a procedure returns {date: new Date()}? If we want to prevent this, we could have a type similar to [..]

    I don't really want to ditch the automatic JSON-serialization. Although if we rewinded time, I might be compelled by the simplicity of this approach.

  5. theshadow27 commented on Jul 15, 2025

    @theshadow27

    I hit this after bringing in tRPC into my project (replacing ~3k SLOC of custom transport, awesome!)

    I get the serialization cleverness but brands are critical when getting into complex multi-entity data models and working with LLMs, since without that type safety they will frequently get different kinds of id strings confused.

    @davazp thank you for the dummy transformer tip - that resolved the issue for me.

    Just curious, with the "new" tanstack react query integration pattern, would it be possible to just define a createRawTRPCContext or something that doesn't have any of the serialization built in? I haven't looked through the code in depth to see how difficult of a change that would be. I guess, since it works with Zod, I figured that the input.parse() function would take care of any conversions needed and there wouldn't be a need for explicit serialization code - but I don't personally have any non-json types (except the brand markers).

    The workaround is only 3 lines of code so I'm not panicked about it 🍻

  6. HarperZ9 commented on Aug 25, 2026

    @HarperZ9

    I'll take a crack at this. Root cause is that a branded tuple is an intersection, not a tuple type, so { [K in keyof T]: ... } stops being homomorphic and collapses to an object shape — .length widens and the brand key gets mapped in.

    Plan: rebuild the tuple recursively so the arity survives, then re-add the brand via the non-array keys:

    type SerializeTuple<T extends readonly [unknown, ...unknown[]]> =
      SerializeTupleElements<T> & Omit<T, keyof any[]>;

    Before I put up a PR — for a NonJsonPrimitive inside a branded tuple like [number, Date, number] & Brand, I'd null the Date slot but keep the arity and the brand. Is that the behavior you'd want?

  7. 1988jimi commented on Aug 31, 2026

    @1988jimi
    Contributor

    @HarperZ9 are you still working on this? I was about to reproduce it on current main, but I don't want to duplicate your work. Happy to leave it with you, or pick it up if you've moved on.

  8. 1988jimi commented on Aug 31, 2026

    @1988jimi
    Contributor

    I tried to reproduce this against current main (6a70335e0) and it appears to be fixed now.

    I added temporary expectTypeOf<Serialize<Source>>().toEqualTypeOf<Source>() assertions for all three forms below:

    • z.tuple([...]).brand('Point') from the current Zod 4 dependency
    • the same schema through zod/v3
    • [number, number, number] & { [brand]: 'Point' } using a unique symbol

    All three pass in serialize.test.ts; the tuple keeps its arity and brand. The focused test file is green with Vitest 4.0.18. I removed the temporary tests after verifying since they don't expose a current regression.

    @HarperZ9 this may save you some time if you were still looking at it. It looks like a later change to the JSON compatibility path fixed the original Zod 3 behavior indirectly.

  9. HarperZ9 commented on Aug 31, 2026

    @HarperZ9

    Thanks for checking current main and documenting the three cases. Based on that, I won’t duplicate implementation work for a regression that appears not to reproduce on current main. The useful remaining question is whether maintainers want one of those cases kept as a regression test; otherwise I’m happy to step back and let the issue close.

  10. trpc-bot commented on Oct 19, 2026

    @trpc-bot
    Collaborator

    🤖 Verified on current main: Serialize<Point> is equal to Point for branded tuples with both Zod 4 and zod/v3 brands (type assertion passes under TypeScript 7.0). Closing; please reopen with a repro on the latest version if you still see this.

  11. github-actions commented on Oct 21, 2026

    @github-actions
    Contributor

    This issue has been locked because we are very unlikely to see comments on closed issues. If you are running into a similar issue, please create a new issue. Thank you.

  12. locked as resolved and limited conversation to collaborators on Oct 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions