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

How do I make this work as expected? #11179

Open
loevgaard opened this issue Dec 4, 2024 · 4 comments
Open

How do I make this work as expected? #11179

loevgaard opened this issue Dec 4, 2024 · 4 comments

Comments

@loevgaard
Copy link

https://psalm.dev/r/a2c22ba1dd

I would like TCallback to either be an int or float. If I use the numeric type it can also be numeric-string which is not intended.

Can I make this work somehow?

Copy link

I found these snippets:

https://psalm.dev/r/a2c22ba1dd
<?php

/**
 * @template TCallback of int|float
 *
 * @param callable():TCallback $callback
 *
 * @return TCallback
 */
function sum(callable $callback, array $items): int|float
{
    return array_sum(array_map($callback, $items));
}
Psalm output (using commit 79ab7e2):

ERROR: InvalidReturnStatement - 12:12 - The inferred type 'float' does not match the declared return type 'TCallback:fn-sum as float|int' for sum

ERROR: InvalidReturnType - 8:12 - The declared return type 'TCallback:fn-sum as float|int' for sum is incorrect, got 'float'

@M393
Copy link

M393 commented Dec 4, 2024

You need to cast the return value of array_sum to TCallback and callable need one parameter of mixed type.
https://psalm.dev/r/fed7db1b92

Copy link

I found these snippets:

https://psalm.dev/r/fed7db1b92
<?php

/**
 * @param callable(mixed):T $callback
 * @return T
 * @template T of int|float
 */
function sum(callable $callback, array $items): int|float
{
    /** @var T $result */
    $result = array_sum(array_map($callback, $items));
    return $result;
}

$_sum_i = sum(static fn (int $i): int => $i, [1, 2, 3]);
$_sum_f = sum(static fn (float $i): float => $i, [1, 2, 3]);
/** @psalm-trace $_sum_f $_sum_i */
Psalm output (using commit 79ab7e2):

INFO: Trace - 17:36 - $_sum_f: float

INFO: Trace - 17:36 - $_sum_i: int

@loevgaard
Copy link
Author

Cool, thanks! Is this expected? I would expect that if a type is either int or string and array_sum returns either int or string then Psalm would put 2 and 2 together

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

2 participants