Serde icon indicating copy to clipboard operation
Serde copied to clipboard

StaticTypeMap breaks on union

Open geek-merlin opened this issue 2 weeks ago • 2 comments

Thanks a lot, this library is so much fun! When playing with it, i found this though:

This one breaks, in the sense that it does NOT add a type key and deserializes to wrong variant:

final class FooBarWrapper {

  public function __construct(
    #[StaticTypeMap(key: 'type', map: [
      'foo' => Foo::class,
      'bar' => Bar::class,
    ])]
    public readonly Foo|Bar $variant,
  ) {}

}

I had to work around it like this:

final class FooBarWrapper {

  public function __construct(
    #[StaticTypeMap(key: 'type', map: [
      'foo' => Foo::class,
      'bar' => Bar::class,
    ])]
    // Serde demands interface typehint, union breaks.
    public readonly CommonFooBarInterface $variant,
  ) {}

}

Not a big issue for me, but principle of least surprise violated.

geek-merlin avatar Dec 18 '25 10:12 geek-merlin