phpstan icon indicating copy to clipboard operation
phpstan copied to clipboard

Contravariant argument produces error with splat operator

Open wimski opened this issue 2 years ago • 0 comments

Bug report

Using contravariance in combination with the splat/spread operator (... / argument overloading) results in an error.

Code snippet that reproduces the problem

This snippet contains two examples:

  1. Passing on a single contravariant argument, which produces no errors.
  2. Passing on multiple (overloaded) contravariant arguments, which produces an error.

https://phpstan.org/r/77c82dd8-795e-4baa-89bc-52da67790e30

Expected output

I expected contravariance to work with overloading without producing an error, because I don't see how that would make a difference. It's just one versus many, but simple contravariance nonetheless.

Did PHPStan help you today? Did it make you happy in any way?

PHPStan in general makes me very happy and helps me almost every day! :smile:

wimski avatar Aug 06 '22 21:08 wimski

The issue is that with PHP8 and named arguments $foo inside the useFoos method can be array<string, Foo> See here: https://3v4l.org/piICI

So that's why PHPStan resolves it to array<int|string, Foo> And when you pass that to a method that expects array<int, FooInterface>, it complains.

You can try to use array<array-key, FooInterface> instead maybe.

canvural avatar Aug 10 '22 10:08 canvural