If, for example, I have a class like this:
class Foo
{
/**
* @var array<string, array{name: string, age: int}>
*/
private array $things;
/**
* @return array
*/
public function getThings(): array
{
return $this->things;
}
}
Then phpstan will give me something along the lines of Method Foo::getThings() return type has no value type specified in iterable type array
.
Of course, I can resolve this by adding the array shape definition to the @return
, but given that I've already defined this on the property, is there a way to avoid duplication here that I'm missing?
My Answer:
One way to avoid duplication in this case is to use a custom type alias for the array shape declaration. This way, you can define the array shape once and reuse it in both the property declaration and the method return type.
Here's an example of how you can do this:
php
class Foo
{
/**
* @var array<string, Thing>
*/
private array $things;
/**
* @return array<string, Thing>
*/
public function getThings(): array
{
return $this->things;
}
}
/**
* @template T
* @psalm-type Thing = array{name: string, age: int}
*/
In this example, we define a custom type alias `Thing` for the array shape declaration. This alias is then used in both the property declaration and the method return type. This way, if the shape of the array needs to be changed in the future, you only need to update it in one place.
Rate this post
3 of 5 based on 4211 votesComments