Home > Blockchain >  How can I avoid repetition of array shape declaration for method return value?
How can I avoid repetition of array shape declaration for method return value?

Time:10-09

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?

CodePudding user response:

No. PHPStan does not read the method body like that to understand what it returns.

You can use local type aliases to reduce the duplication:

/** @phpstan-type Things array<string, array{name: string, age: int}> */
class Foo
{
   /**
    * @var Things
    */
   private array $things;

   /**
    * @return Things
    */
   public function getThings(): array
   {
      return $this->things;
   }
}
  • Related