admin管理员组文章数量:1208155
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?
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?
Share Improve this question asked Jan 19 at 16:02 Roman HockeRoman Hocke 4,2391 gold badge21 silver badges35 bronze badges 3 |1 Answer
Reset to default 2I use template T because I need to preserve any other keys that may be present in the argument.
That's perhaps the hint needed here.
More specifically, you are using T
as an intersection type for @return with something that is not a type: array{} shape.
As has been outlined in phpstan / phpstan Array intersection support #4703 (github.com) the ampersand &
of an intersection type does not compute array shapes and likewise it does not the T
template in your example.
What you may expect from PHPStan according to ondrejmirtes in February 2024 is as following:
PHPStan WILL NOT add support for "array intersections" but WILL ADD support for "array shapes with extra keys with known type" using this syntax:
array{a: mixed, ...<array-key, mixed>}
(same as recently added in Psalm).Please follow this issue to get the updates: #8438 (github.com)
本文标签: phpSpecifying keys in array shape in PHPstanStack Overflow
版权声明:本文标题:php - Specifying keys in array shape in PHPstan - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738732318a2109393.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
@return array{a: string, x: int}
phpstan.org/r/7e983392-a5bb-47b9-94bf-5d9fc2697b5b -- for details see the answer – hakre Commented Jan 19 at 16:52