I have defined an interface for an ordered list. The class docblock looks like this:
/**
* Interface ListOrderedInterface
* @template ListOrderedElement
*/
Within the method docblocks for this interface, ListOrderedElement is used to ensure that the type of thing being added to the list is consistent. PHPStan runs clean on ListOrderedInterface.php. So far so good.
Next I defined an interface for a factory that makes an ordered list. The definition looks like this:
/**
* Class ListFactoryInterface
*/
interface ListOrderedFactoryInterface
{
/**
* makeList
* @return ListOrderedInterface
*/
public function makeList(): ListOrderedInterface;
}
phpstan is complaining with the warning message "phpstan:: Method makeList return type with generic interface ListOrderedInterface does not specify its types". I don't know how to specify the types for the interface.
Thanks for helping with this.
CodePudding user response:
You need provide a specialization for your ListOrderedInterface in the makeList phpdoc in the @return part.
interface ListOrderedFactoryInterface
{
/**
* This is an example with a concrete type, syntax is <type>
* @return ListOrderedInterface<string>
*/
public function makeList(): ListOrderedInterface;
}
If you need this to generic as well, you would need to add the @template on the factory also and return a generic type from makeList.
/**
* @template T
*/
interface ListOrderedFactoryInterface
{
/**
* @return ListOrderedInterface<T>
*/
public function makeList(): ListOrderedInterface;
}
And in the classes that implement FactoryInterface, add the @implements phpdoc.
/**
* Instead of string put the actual type it should return
* @implements ListOrderedFactoryInterface<string>
*/
class ConcreteFactory implements ListOrderedFactoryInterface
{
}
You can find more examples in the official docs: https://phpstan.org/blog/generics-by-examples