标签: array-shape

PHPStan 转换为更具体的数组形状

在我的代码中,我调用一个方法,其返回值的类型如下:

/**
 * @return array<int, array<string,mixed>>
 */
public function fetchAllAssociative(): array;
Run Code Online (Sandbox Code Playgroud)

子类型array<string, mixed>以通用方式描述数据库记录。我确切地知道这个数据库记录是什么样的,所以我想更具体地记录该方法:

/**
 * @return array<int, array{id: int, firstName: string, lastName: string}>
 */
public function getAllUsers(): array
{
  return $this->userRepository->fetchAllAssociative();
}
Run Code Online (Sandbox Code Playgroud)

然而,PHPStan 抱怨说我应该完全按照以下方式键入我的方法fetchAllAssociative

Method UserRepository::getAllUsers() should return array<int, array{id: int, firstName: string, lastName: string}> but returns array<int, array<string, mixed>>.

有办法投吗?我的解决方法是引入一个新变量并使用@var标签,但我不太喜欢它(其他静态代码分析工具也不喜欢它)

/**
 * @return array<int, array{id: int, firstName: string, lastName: string}>
 */
public function getAllUsers(): array
{
  /**
   * @var array<int, array{id: int, firstName: …
Run Code Online (Sandbox Code Playgroud)

phpstan array-shape

5
推荐指数
1
解决办法
623
查看次数

标签 统计

array-shape ×1

phpstan ×1