Skip to content

Defining templates TCollection and TItem on function does not let me specify TCollection<TItem> as a @return #9807

@simensen

Description

@simensen

Bug report

I'm creating helpers for a generic collection library. I've used @template TItem/class-string<TItem> function parameters successfully. I assumed the following would work, but it claims $items @param and @return have unresolvable types.

I guess there needs to be a way to specify that @template TCollection is generic.

<?php

declare(strict_types=1);

namespace Acme\Util\Collections;

use Acme\Util\Collections\SetCollection\SetCollection;
use Acme\Util\Collections\SetCollection\SetCollectionHelper;

final readonly class CollectionHelper
{
    /**
     * @template TCollection
     * @template TItem
     *
     * @param class-string<TCollection> $collectionType
     * @param class-string<TItem> $itemType
     * @param array<TItem>|TCollection<TItem>|TItem|null ...$items
     *
     * @return TCollection<TItem>
     */
    public static function reduce(string $collectionType, string $itemType, mixed ...$items): mixed
    {
        if ($collectionType === SetCollection::class) {
            return SetCollectionHelper::reduce($itemType, ...$items);
        }

        throw new \LogicException('Unknown type of collection.');
    }
}

Code snippet that reproduces the problem

https://phpstan.org/r/f160f226-086d-44f1-86ce-d0c5f2c036b5

Expected output

I expected I could specify two template types (TCollection and TItem) via function arguments and refer to both in the @return declaration and specify TCollection's generic as TItem (TCollection<TItem>).

Did PHPStan help you today? Did it make you happy in any way?

PHPStan helped me spend time tracking down inconsistencies in my code. :)

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