psalm
psalm copied to clipboard
Template as array key
Discussed in https://github.com/vimeo/psalm/discussions/7901
Originally posted by Baptouuuu April 26, 2022 Is there a way to use a template to specify a key of an array like so : https://psalm.dev/r/7469115e9c ?
toArray('i', 1)
=> array{i: int}
I found these snippets:
https://psalm.dev/r/7469115e9c
<?php
/**
* @template K of string
* @template V
* @return array{K: V}
*/
function toArray(string $key, mixed $value): array
{
return [$key => $value];
}
$a = toArray('foo', 42);
echo $a['foo'];
Psalm output (using commit b5b5c20):
INFO: LessSpecificReturnStatement - 10:12 - The type 'non-empty-array<string, mixed>' is more general than the declared return type 'array{K: V:fn-toarray as mixed}' for toArray
INFO: MoreSpecificReturnType - 6:12 - The declared return type 'array{K: V:fn-toarray as mixed}' for toArray is more specific than the inferred return type 'non-empty-array<string, mixed>'
ERROR: InvalidArrayOffset - 14:6 - Cannot access value on variable $a using offset value of 'foo', expecting 'K'
INFO: MixedArgument - 14:6 - Argument 1 of echo cannot be mixed, expecting string
That would be amazing 👍
Also interested in this