-
-
Notifications
You must be signed in to change notification settings - Fork 932
How to annotate a class that can handle a/any generic class? #6656
-
I've set up the following contrived example to show my question:
https://phpstan.org/r/c35368f8-d6fa-4a1c-bb4a-555fa7972855
interface Collectable {} /** * @template T of Collectable */ interface CollectionInterface {} class Collector { public function collect(CollectionInterface $collection): void {} }
This results in:
Method Collector::collect() has parameter $collection with generic interface CollectionInterface but does not specify its types: T
How do I annotate Collector to show it handles any CollectionInterface? I could add a /** @param CollectionInterface<Collectable> $collection */ to the collect method to satisfy the analysis, but this adds a noisy comment and no new information.
Beta Was this translation helpful? Give feedback.
All reactions
Yes, writing /** @param CollectionInterface<Collectable> $collection */ is the right way. You need to decide that and tell that to PHPStan, it can't assume that on your behalf. You can turn off this check with this setting: checkGenericClassInNonGenericObjectType: false (https://phpstan.org/config-reference#vague-typehints)
Replies: 1 comment 2 replies
-
Yes, writing /** @param CollectionInterface<Collectable> $collection */ is the right way. You need to decide that and tell that to PHPStan, it can't assume that on your behalf. You can turn off this check with this setting: checkGenericClassInNonGenericObjectType: false (https://phpstan.org/config-reference#vague-typehints)
Beta Was this translation helpful? Give feedback.
All reactions
-
Ok, thanks. Can I do that for the entire class at once? Say it has a number of methods, all expecting or returning CollectionInterface<Collectable> where the type hint is CollectionInterface.
Beta Was this translation helpful? Give feedback.
All reactions
-
You can make it shorter with local type aliases: https://phpstan.org/writing-php-code/phpdoc-types#local-type-aliases
Beta Was this translation helpful? Give feedback.