psalm icon indicating copy to clipboard operation
psalm copied to clipboard

Template as array key

Open AndrolGenhald opened this issue 2 years ago • 2 comments

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}

AndrolGenhald avatar Apr 27 '22 14:04 AndrolGenhald

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

psalm-github-bot[bot] avatar Apr 27 '22 14:04 psalm-github-bot[bot]

That would be amazing 👍

kkmuffme avatar Sep 30 '22 01:09 kkmuffme

Also interested in this

provokateurin avatar Jun 14 '23 05:06 provokateurin