Skip to content

anyOf generation is wrong and often cannot be deserialized #414

Open

Description

@ahl

The current handling of anyOf is pretty simple:

#[derive(Serialize, Deserialize)]
pub struct AnyOfType {
    #[serde(flatten)]
    subtype_0: Option<SubType0>,
    #[serde(flatten)]
    subtype_1: Option<SubType1>,
...
}

This seemed reasonable--and still may... until you think about it. First, an anyOf means that at least one of the subschemas must be valid. This structure does nothing to enforce that constraint. Second, the subtypes might have overlap or even conflicts which means that deserialization could fail.

Instead I propose that we treat an anyOf like a oneOf (i.e. an enum) where we take the power set of subtypes:

anyOf: [a, b, c]
oneOf: [a, b, c, { allOf: [a, b] }, { allOf: [a, c] }, { allOf: [b, c] }, { allOf: [a, b, c] }]

Note that some of those allOf combinations might be invalid in which case they would be ignored (and would therefore not turn into an enum variant); others might be redundant in which case they can also be ignored. Currently, we check if all variants are mutually exclusive and can therefore be trivially treated as a oneOf (i.e. [a, b, c]); this would fall out as a consequence of attempting to resolve the allOf subschemas.

The resulting type would look something like this:

#[derive(Serialize, Deserialize)]
#[serde(untagged)]
pub enum AnyOfType {
    Variant0: TypeA,
    Variant1: TypeB,
    Variant2: TypeC,
    Variant3: TypeAB,
...
    Variant7: TypeABC,
}

Activity

  1. ndreno commented on Mar 19, 2026

    @ndreno

    We've implemented a fix for this in our fork at barbacane-dev/typify. Happy to extract a clean PR if there's interest.

  2. added
    typify2fixed or enabled in the typify2 re-write
    on Nov 17, 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

    Labels

    typify2fixed or enabled in the typify2 re-write

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions