Skip to content
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

Template without common ancestor #11287

Open
jornane opened this issue Feb 15, 2025 · 1 comment
Open

Template without common ancestor #11287

jornane opened this issue Feb 15, 2025 · 1 comment

Comments

@jornane
Copy link
Contributor

jornane commented Feb 15, 2025

https://psalm.dev/r/9d4c7819b6

When using @template T in a function, Psalm assumes that there is a common ancestor for T, but this may not be the case, for example when array<T> is used.

In the example, a parameter to the function is array<class-string<T>,callable(T):string>,
meaning a class and a function that takes an object of this class to convert it to a string. T may for example be DateTime or DateInterval, these have no common ancestor.

Copy link

I found these snippets:

https://psalm.dev/r/5a52410f7d
<?php
/**
 * @template T
 *
 * @param array<object> $data
 * @param array<class-string<T>,callable(T):string> $transform
 * @return array<object|string>
 */
function transform( array $data, array $transform = [] ): array {
	foreach( $data as $key => $value ) {
		foreach( $transform as $class => $transformer ) {
			if ( is_a( $value, $class ) ) {
				$data[$key] = $transformer( $value );
			}
		}
	}
	return $data;
}

class A {
	public function __construct(public readonly string $aValue) {}
}
class B {
	public function __construct(public readonly string $bValue) {}
}

var_export(transform(
	[new A('A'), new B('B')],
	[
		A::class => fn(A $a) => $a->aValue,
		B::class => fn(B $b) => $b->bValue,
	]
));
Psalm output (using commit 20a21f9):

ERROR: InvalidArgument - 27:12 - Type B should be a subtype of A

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant