psalm icon indicating copy to clipboard operation
psalm copied to clipboard

Return type: subtype of type

Open distantnative opened this issue 3 months ago • 1 comments

How can I type hint of the subtype/template of a type/template?

https://psalm.dev/r/58e26f6817

In this example, how can I hint that the return value will be of type TA corresponding to whichever TClass type $item is?

distantnative avatar Apr 11 '24 10:04 distantnative

I found these snippets:

https://psalm.dev/r/58e26f6817
<?php

class Element {}

/**
 * @template TA
 */
class A {
  /**
   * @param TA $item
   */
  public function __construct(
    protected $item
  ) {}

  /**
   * @return TA
   */
  public function get()
  {
    return $this->item;  
  }
}

/**
 * @extends A<Element>
 */
class B extends A {
}


/**
 * @template TClass
 */
class C {
  /**
   * @param TClass $item
   */
  public function __construct(
    protected $item
  ) {}

  /**
   * @return TClass[TA]
   */
  public function foo() {
    return $this->item->get();
  }
}
Psalm output (using commit ef3b018):

ERROR: InvalidDocblock - 46:3 - Unrecognised template param TA in docblock for C::foo

INFO: MixedMethodCall - 47:25 - Cannot determine the type of $this->item when calling method get

INFO: MissingReturnType - 46:19 - Method C::foo does not have a return type

psalm-github-bot[bot] avatar Apr 11 '24 10:04 psalm-github-bot[bot]