rust-typescript-type-def icon indicating copy to clipboard operation
rust-typescript-type-def copied to clipboard

Add support for `#[serde(untagged)]` attributes on individual enum variants

Open regexident opened this issue 9 months ago • 0 comments

By lacking support for #[serde(untagged)] attributes on individual enum variants the crate fails to support a common pattern for modeling string-based enums:

type Kind = "foo" | "bar" | "baz" | "blee" | string;
#[derive(Serialize, TypeDef)]
#[serde(rename_all = "kebab-case")]
pub enum Kind {
    Foo,
    Bar,
    Baz,
    Blee,
    #[serde(untagged)]
    Unknown(String),
}

Deserializing unknown "kind" values as Kind::Unknown(…) makes Kind future-proof, which is particularly import in scenarios where one does not control the source providing the serialized representations of Kind, but also has a requirement to never fail on unexpected values.

In the particular scenario above the following would work just fine, as is:

#[derive(Serialize, TypeDef)]
#[serde(untagged, rename_all = "kebab-case")]
pub enum Kind {
    Foo,
    Bar,
    Baz,
    Blee,
    Unknown(String),
}

… but there are other scenarios where an enum-level #[serde(untagged)] is undesirable, such as if individual "known" variants had additional fields.

regexident avatar May 11 '25 20:05 regexident