PHPStan error: @return type is incompatible with native type (generics and static)

1.9k Views Asked by At

I'm struggling to understand the cause of PHPStan error on method FooArray::this_doesnt_work.

PHPDoc tag @return with type FooArray<int|string, TValueIn> is incompatible with native type static(FooArray<TKey of (int|string), TValue>).

Could anyone shed a light on this?

<?php declare(strict_types = 1);

/**
 * @template TKey of array-key
 * @template TValue
 *
 * @template-extends \ArrayObject<TKey, TValue>
 */
class FooArray extends \ArrayObject {

    /**
     * @param array<TKey, TValue> $array
     */
    final public function __construct(array $array = []) {
        parent::__construct($array, 0, \ArrayIterator::class);
    }

    /**
     * @template TValueIn
     *
     * @param TValueIn ...$items
     *
     * @return static<int|string, TValueIn>
     */
    public static function this_doesnt_work(mixed ...$items): static {
        return new static($items);
    }
}

/**
 * @template TValueIn
 *
 * @param TValueIn ...$items
 *
 * @return FooArray<int|string, TValueIn>
 */
function this_works(mixed ...$items): FooArray {
    return new FooArray($items);
}

See live: https://phpstan.org/r/d0806e2c-4250-4adc-83f6-f002f6efa476

0

There are 0 best solutions below