Type key exists pattern
#14042
-
|
Is it possible to make the following work: https://phpstan.org/r/fd128ae5-e0d1-4c0f-8682-f2bbfa18679c <?php declare(strict_types = 1);
use function PHPStan\dumpType;
use function PHPStan\Testing\assertType;
class Arr
{
/**
* @template TKey of string
* @param array<TKey, mixed> $arr
* @return ($key is TKey ? true : false)
*/
public static function keyExists(array $arr, string $key): bool
{
return array_key_exists($key, $arr);
}
}
dumpType(Arr::keyExists(['a' => 1], 'a')); // true ✓
dumpType(Arr::keyExists(['a' => 1], 'b')); // true ✘ (should be false)
dumpType(Arr::keyExists(['a' => 1, 'b' => 2], 'a')); // true ✓
dumpType(Arr::keyExists(['a' => 1, 'b' => 2], 'b')); // true ✘ (should be false) |
Beta Was this translation helpful? Give feedback.
Answered by
mspirkov
Feb 1, 2026
Replies: 1 comment 3 replies
-
|
I think you need something like this: https://phpstan.org/r/7176000b-7c49-46e5-a4c7-cc76c919eb9b |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
shaedrich
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think you need something like this: https://phpstan.org/r/7176000b-7c49-46e5-a4c7-cc76c919eb9b