Interpret type from already defined @template Generic which is itself a Generic #9053
-
I'm asking if something like this is maybe already possible. I have a generic like this: /**
* @implements ModelInterface<Child>
*/
class Model implements ModelInterface
{
}
/**
* @template T of ChildInterface
*/
interface ModelInterface {
}
/**
* @implements ChildInterface<Model>
*/
class Child implements ChildInterface
{
}
/**
* @template T of ModelInterface
*/
interface ChildInterface {
} And a service which is something like this The full example can be found here as I think else its very confusing: https://phpstan.org/r/d4c0e34b-096b-41c2-ab96-a143980a0765 I'm not sure if something like this |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 9 replies
-
I looked at your example and implemented the one missing piece - a way to extract template type from an existing type, an equivalent to calling So working code now looks like this: /**
* @template-covariant T of ModelInterface
*/
class Helper
{
/**
* @param T $model
*/
public function __construct(private ModelInterface $model)
{}
/**
* @return template-type<T, ModelInterface, 'TChild'>
*/
public function getFirstChildren(): ChildInterface
{
$firstChildren = $this->model->getChildren()[0] ?? null;
if (!$firstChildren) {
throw new \RuntimeException('No first child found.');
}
return $firstChildren;
}
} Updated playground: https://phpstan.org/r/d734d19d-f9d1-4cc3-813f-65ef69d04454 |
Beta Was this translation helpful? Give feedback.
I looked at your example and implemented the one missing piece - a way to extract template type from an existing type, an equivalent to calling
Type::getTemplateType()
: https://apiref.phpstan.org/1.10.x/PHPStan.Type.Type.html#_getTemplateTypeSo working code now looks like this: