Static analysis
PHPStan
Generics work out of the box: Users::of($order) is an error, $users->first() is User, $users->filter(...) is Users, $users->groupBy(...) is ImmutableMap<K, Users>.
The package also ships an extension that checks the declared type against @extends:
includes:
- vendor/eugeneerg/collections/extension.neon/** @extends ImmutableList<User> */
final readonly class Users extends ImmutableList
{
protected const TYPE = Order::class; // classConstant.phpDocType: TYPE does not match @extends
}A collection class without @extends is a missingType.generics error. Include the file by hand: phpstan/extension-installer loads only packages of the phpstan-extension type, and this one is a library.
PHPStan 2.3.7 or newer is required; Composer refuses older versions, which report false errors for the check.
Psalm
Generics and element types work the same way: first() is User, builder()->build() is Users, Users::of(1) is an error. Psalm cannot compare TYPE with @extends, so that mismatch is left to the runtime check.
Typed results without a class
A base collection created empty, such as ImmutableMap::empty() or ImmutableMap::builder(), has no known types, so closures with typed parameters do not fit it. Start from data (fromIterable()), use foldBy() (both sides are inferred from the closures), or declare a small class with KEY_TYPE and VALUE_TYPE.
$totals = $postings->foldBy(
fn(Posting $p) => $p->amount->currency,
0,
fn(int $sum, Posting $p) => $sum + $p->amount->cents,
); // ImmutableMap<Currency, int>