Psalm: Typing array values as mixed explicitly during iteration

Created on 16 Aug 2019  路  5Comments  路  Source: vimeo/psalm

My apologies for posting again, but this report is a bit different, even though it's a followup for the https://github.com/vimeo/psalm/issues/2024 and https://github.com/vimeo/psalm/issues/652

Imagine there is the following code

<?php

function keys(): array
{
  return ['foo', 'bar'];
}

// no lines above can be changed

foreach (keys() as $k) {
  echo gettype($k);
}

https://psalm.dev/r/156e52eb66

As of now it's impossible to type it to pass linting with totallyTyped mode.

The only way I found (as answered at https://stackoverflow.com/q/57519071/251311) is to use ugly hacks via array_keys.

I believe it's a frequent enough case to support something like

foreach (keys() as /** @var mixed $k */ $k) {
  echo gettype($k);
}

Most helpful comment

@weirdan that doesn't throw errors now, thanks to @lhchavez's fix: https://psalm.dev/r/2e6094ec97

All 5 comments

@muglug I think the following should not throw errors:

/** @var mixed $k */
foreach (keys() as $k) {
  echo gettype($k);
}

Any other type in @var are fine here, except explicit mixed.

I think there are two directions to go here - the first is to think about explicit vs implicit mixed, at least in the context of foreach assignment. The second (much simpler) option would be to separate MixedForeachAssignment out from MixedAssignment so it could be suppressed independently.

@weirdan that doesn't throw errors now, thanks to @lhchavez's fix: https://psalm.dev/r/2e6094ec97

Do we close this now then?

Yeah seems ok to

Was this page helpful?
0 / 5 - 0 ratings