I want to annotate function, tat takes array with at least key "a" and returns the same array shape with newly added key "x". I tried using type intersection like this:
/**
* @template T of array{a: string}
* @param T $p
* @return T&array{x: int}
*/
function addXToArray(array $p) {
$p['x'] = strlen($p['a']);
return $p;
}
$result = addXToArray(['a' => 'hello']);
This is obviously not the correct way, because PHPstan complains (on level 10 with "Treat PHPDoc types as certain"):
PHPDoc tag @return contains unresolvable type.
I use template T because I need to preserve any other keys that may be present in the argument.
How do I correctly annotate the function?
@return array{a: string, x: int}phpstan.org/r/7e983392-a5bb-47b9-94bf-5d9fc2697b5b -- for details see the answer