Skip to content

checkBenevolentUnionTypes + @template TKey of array-key = false positive #9766

@LastDragon-ru

Description

@LastDragon-ru

Bug report

I'm trying to enable checkBenevolentUnionTypes (as recomended in #9750), but seems I found something stange :)

<?php declare(strict_types = 1);

/**
 * @template TKey of array-key
 * @template TItem
 */
class PHPStanBug {
    /**
     * @param iterable<TKey, TItem> $items
     */
    public function __construct(
        private iterable $items,
    ) {
        // empty
    }

    /**
     * @return iterable<TKey, TItem>
     */
    protected function getItems(): iterable {
        return $this->items;
    }
}

PHPStan will report that:

 21     Method PHPStanBug::getItems() should return iterable<TKey of (int|string), TItem> but returns iterable<TKey of (int|string), TItem>.
         💡 Type int is not always the same as TKey. It breaks the contract for some argument types, typically subtypes.
         💡 Type string is not always the same as TKey. It breaks the contract for some argument types, typically subtypes.

With @template TKey of string|int there are no errors.

Code snippet that reproduces the problem

https://phpstan.org/r/3a30aea2-ea44-4546-8774-3a9589abe496

Expected output

Probably no error?

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

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions