Score:6

How to override the typehint for entityTypeManager with a more specific one?

cn flag

I'm often frustrated by entityTypeManager because when I load entities, the typehint for the return value of the load methods is EntityInterface, but I want it to be a more specific interface (which I know it will be because I am loading a specific entity type with getStorage).

So, for example, consider this code adapted from the Flag module:

  /**
   * Loads flagging entities given their IDs.
   *
   * @param int[] $ids
   *   The flagging IDs.
   *
   * @return \Drupal\flag\FlaggingInterface[]
   *   An array of flaggings.
   */
  private function getFlaggingsByIds(array $ids): array {
    return $this->entityTypeManager->getStorage('flagging')->loadMultiple($ids);
  }

PHPStan points out that there is a return type mismatch here because the doc comment is FlaggingInterface[] but loadMultiple() resolves to EntityInterface[].

I can fix this by rewriting as follows:

$ids = $this->entityTypeManager->getStorage('flagging')->loadMultiple($ids);
/** @var \Drupal\flag\FlagInterface[] $ids */
return $ids;

But then I have to introduce an extra variable just to get the correct typehint. Is there a more efficient way to override the typehint in this kind of case?

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.