Type hinting `|Type[]` returns, when not a technical possibility
Rarst opened this issue · comments
Bug Report
Information | Description |
---|---|
Version | 5.1.0 |
PHP version | 8.2.1 |
OS Platform | Windows 10 |
Summary
Some of the methods type hint a possibility of |Type[]
return, while their implementation can never produce such.
Standalone code, or other way to reproduce the problem
$this->datePeriod = $period->dateRangeForward('1 day');
Expected result
No type issues with such assignment for the property typed as DatePeriod
.
Actual result
Psalm reports the following error:
ERROR: PossiblyInvalidPropertyAssignmentValue - src/Tv/Collection/Days.php:30:29 - $this->datePeriod with declared type 'DatePeriod' cannot be assigned possibly different type 'DatePeriod<DateTimeInterface|string>|array<array-key, DateTimeImmutable>' (see https://psalm.dev/147)
$this->datePeriod = $period->dateRangeForward('1 day');
From my reading @return DatePeriod|DateTimeImmutable[]
is used to communicate that the return is like an array of DateTimeImmutable
objects, however in technical sense the return of such an array is never a possibility - the return is implemented as strictly DatePeriod
and typed as such in the method signature.
My personal practice in such case would probably be @return DatePeriod<DateTimeImmutable>
(or Psalm-specific @psalm-return DatePeriod<DateTimeImmutable>
), which would be both human-readable and technically correct for tools that understand template notation.
From quick look there are several more methods with similar approach to the return hints.
@Rarst indeed the correct docblock should be DatePeriod<DateTimeImmutable>
but I think that either phpstan or PHPStorm complains about it. I do not remember which one.
The approximation of @return DatePeriod|DateTimeImmutable[]
means that it will return a DatePeriod or a collection of DateTimeImmutable object not an array per se.
Either way I am open to a PR to correct/improve the docblock. As long as it makes PHPStan happy, I will be happy 😉
PhpStorm is fine about it for me (it improved a lot about these things across several more recent releases, they aim to support everything Psalm does). I'll try tinker on a PR and see how PHPStan likes it at the moment.