psalm icon indicating copy to clipboard operation
psalm copied to clipboard

psalm does not report possibly undefined array key when using a generic `int` type as an index.

Open azjezz opened this issue 6 months ago • 4 comments

Example: https://psalm.dev/r/a21dfe9400

This could return null at runtime ( and result in a warning ) if call like this: get_index(1, [0 => 'foo']);

azjezz avatar Jun 21 '25 16:06 azjezz

I found these snippets:

https://psalm.dev/r/a21dfe9400
<?php

/**
 * @param array<int, string> $messages
 */
function get_index(int $code, array $messages): null|string
{
    return $messages[$code];
}
Psalm output (using commit 6670889):

INFO: LessSpecificReturnType - 6:49 - The inferred return type 'string' for get_index is more specific than the declared return type 'null|string'

psalm-github-bot[bot] avatar Jun 21 '25 16:06 psalm-github-bot[bot]

You need to enable https://psalm.dev/docs/running_psalm/configuration/#ensurearrayintoffsetsexist (I don't think its available in the playground).

weirdan avatar Jun 22 '25 12:06 weirdan

@weirdan shouldn't the result still be null|string regardless if an issue is emitted or not?

azjezz avatar Jun 22 '25 13:06 azjezz

shouldn't the result still be null|string regardless if an issue is emitted or not?

If it didn't affect the inference, having this option would be quite pointless, as users would be forced to do additional checks anyway.

However, it appears Psalm currently does not emit PossiblyUndefinedIntArrayOffset on array<int, T>[int] where latter int is not a literal type, regardless of the option value, so the point is moot. If it were to be fixed though, you'd get the behaviour you need as an opt-in feature.

weirdan avatar Jun 22 '25 13:06 weirdan