やりたいこと
"no value type specified in iterable type array"を解消したい
エラー内容・原因
エラーの原因は2つ
- getInputsの$argvに代入されている配列の構成要素が明示されていない
- 戻り値の配列の構成要素が明示されていない
コード
const SEPARATE_EACH_2 = 2;
function getInputs(array $argv): array
{
$inputs = array_slice($argv, 1);
return array_chunk($inputs, SEPARATE_EACH_2);
}
$inputs = getInputs(['test', 10, 50, 80, 100]);
結果
5 Function getInputs() has parameter $argv with no value type specified in iterable type array.
💡 See: https://phpstan.org/blog/solving-phpstan-no-value-type-specified-in-iterable-type
5 Function getInputs() return type has no value type specified in iterable type array.
💡 See: https://phpstan.org/blog/solving-phpstan-no-value-type-specified-in-iterable-type
[ERROR] Found 2 errors
解決策
-
$argvに代入されている配列のkeyは「int」で、要素は「string」と「int」で構成されている
['test', 10, 50, 80, 100] -
戻り値は2次元配列となっており、配列のkeyと要素ともに「int」で構成されている
[[10,50],[80,10]]
修正後のコード
const SEPARATE_EACH_2 = 2;
/**
*
* @param array<int,mixed> $argv
* @return array<array<int,int>>
*/
function getInputs(array $argv): array
{
$inputs = array_slice($argv, 1);
return array_chunk($inputs, SEPARATE_EACH_2);
}
$inputs = getInputs(['test', 10, 50, 80, 100]);
結果
1/1 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%
[OK] No errors
まとめ
検知数があまりにも多い場合には、すべての配列に対して構成要素を明示することが必要なのか検討すべきではないかと思いました。