-
Notifications
You must be signed in to change notification settings - Fork 661
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Incorrect type inference when using key
/current
/reset
on non-empty array
#8521
Comments
I found these snippets: https://psalm.dev/r/bc365e8080<?php
/** @var array<string,int> */
$foo = [];
if ($foo === []) {
return;
}
$string = key($foo);
$int = current($foo);
/**
* @psalm-trace $string
* @psalm-trace $int
*/
|
key
/current
on non-empty arraykey
/current
/reset
on non-empty array
Yeah, that looks like it would work :) In fact, you can check that it does by just renaming the functions: https://psalm.dev/r/b9f82704bf Note that is theory, a non-empty-list is a non-empty-array so you should be able to simplify your condition by getting rid of the non-empty-list case (for current and reset at least) PS: internal functions are typed through the callmap when they're simple enough. If some conditional magic needs to be applied, stubs take priority, then if you need to have specialized code, TypeProviders can override all that. Here you should be able to add a stub (or rather adapt it) in CoreGenericFunctions.phpstub |
I found these snippets: https://psalm.dev/r/b9f82704bf<?php
/** @var array<string,int> */
$foo = [];
if ($foo === []) {
return;
}
$string = key2($foo);
$int = current2($foo);
/** @psalm-trace $string */;
/** @psalm-trace $int */;
/**
* @template T of array-key
* @param array<T,mixed> $array
* @return ($array is non-empty-list ? 0|positive-int : ($array is non-empty-array ? T : mixed))
*/
function key2(array $array): mixed
{
}
/**
* @template T
* @param array<mixed,T> $array
* @return ($array is non-empty-list ? T : ($array is non-empty-array ? T : T|false))
*/
function current2(array $array): mixed
{}
/**
* @template T
* @param array<mixed,T> $array
* @return ($array is non-empty-list ? T : ($array is non-empty-array ? T : T|false))
*/
function reset2(array $array): mixed
{}
|
Nice, I'll give that a try when I find some time. |
It's okay :) We're short staffed too! Issues are still useful for other users when searching an issue or to centralize discussions |
Hey there,
when both key and value types of an array are known, I'd expect psalm to be able to infer the return value of
key
/current
in case of anon-empty-array
ornon-empty-list
.https://psalm.dev/r/bc365e8080
Not sure if this can already be done with some conditional magic (even tho, I did never understood how these internal functions are typed 😅).
But something like this might work, right?
The text was updated successfully, but these errors were encountered: