Skip to content

Narrow type in Collection::filter() #697

@whataboutpereira

Description

@whataboutpereira

It would be great if Collection::filter() would also be able to narrow types.

class Group extends Node
    /**
     * @var Collection<int, Node>
     */
    #[ORM\OneToMany(targetEntity: Node::class, mappedBy: 'parent')]
    private Collection $children;

    /**
     * @return Collection<int, Group>
     */
    public function getGroups(): Collection
    {
        return $this->children
            ->filter(static fn (Node $node): bool => $node instanceof Group)
        ;
    }
}

Yields:

Method App\Entity\Group::getGroups() should return Doctrine\Common\Collections\Collection<int, App\Entity\Group>
but returns Doctrine\Common\Collections\Collection<int, App\Entity\Node>.

A workaround is to convert to an array.

    /**
     * @return array<int, Group>
     */
    public function getGroups(): array
    {
        return array_filter(
            $this->children->toArray(),
            static fn (Node $node): bool => $node instanceof Group
        );
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions