Skip to content

Fields on generic interfaces cannot be generic #3602

@thearchitector

Description

@thearchitector

Describe the Bug

Generics that have been decorated with @strawberry.interface are unable to define fields with generic return types. However, the same field seems to work fine if the generic is decorated as a type instead.

The following code:

from typing import Generic, TypeVar

import strawberry

T = TypeVar("T")


@strawberry.interface
class GenericInterface(Generic[T]):
    obj: strawberry.Private[T]

    @strawberry.field
    def as_list(self) -> list[T]:
        return [self.obj]


@strawberry.type
class GenericObject(GenericInterface[int]):
    pass


@strawberry.type
class Query:
    @strawberry.field
    def numbers(self) -> GenericObject:
        return GenericObject(obj=1)


res = strawberry.Schema(query=Query).execute_sync(
    """
        query {
            numbers {
                asList
            }
        }
    """
)
print(res)

produces the error:

TypeError: GenericInterface fields cannot be resolved. The type "<strawberry.type.StrawberryList object at 0x7e3c02eaece0>" is generic, but no type has been passed

If you replace @strawberry.interface with @strawberry.type, the error goes away and the query returns what I would expect:

ExecutionResult(data={'numbers': {'asList': [1]}}, errors=None, extensions={})

System Information

  • Operating system: Linux
  • Strawberry version (if applicable): 0.237.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions