strawberry icon indicating copy to clipboard operation
strawberry copied to clipboard

Add support for `Annotated[A | B, strawberry.union(name="SomeUnion")]`

Open patrick91 opened this issue 3 years ago • 0 comments

So, I've been thinking a bit about our strawberry.union function, and while I think it provides a good API, we can't unfortunately make it properly type safe.

Currently the way strawberry.union works is that it returns a StrawberryUnion instance, which is fine[1], but the fact we are doing a function call makes the type checkers complain.

It currently works in Mypy because we have our custom plugin, but for example if fails on Pyright with the following error:

Illegal type annotation: variable not allowed unless it is a type aliasPylance[reportGeneralTypeIssues]

unfortunately looks like there's might never be support for function calls to create types, which is a shame.

Anyway, I think we should be type-checkers friendly and at least provide an alternative to strawberry.union, Annotated is probably a good solution for this because we use it already and it is the standard way of attaching metadata to types.

It would work like this:

SubscribeToPodcastResponse = Annotated[
    SubscribeToPodcastSuccess | PodcastNotFound | AlreadySubscribedToPodcast,
    strawberry.union("SubscribeToPodcastResponse"),
]

[1] maybe, the more I think about this the more I think we should use the python type system as much as we can, but that's for a future discussion

patrick91 avatar Jul 08 '22 21:07 patrick91