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

Proposal: a way to express template arguments when returning callables|return inferred type #5530

Open
danog opened this issue Mar 30, 2021 · 3 comments

Comments

@danog
Copy link
Collaborator

danog commented Mar 30, 2021

Currently, there is no way in psalm to express a function that returns a callable, if the callable has standalone template arguments.

For example: https://psalm.dev/r/7be6130bcb

I can call the templated function identity, and expect it to return exactly the provided type.
However, the makeIdentity function will not work as expected, unless I manually specify the templated type of the returned callable using a @var annotation.

Of course, I can't use the returned callable and expect it to work as the identity function, precisely because I set a specific template type when creating the function (if I hadn't provided any type, psalm would've defaulted to empty).

What I think would be really neat to have is a way to express this inside of psalm, either as:

  • a @template-return annotation that is related to a returned callable
  • a @psalm-infer-return to allow returning exactly the inferred type (aka exactly the templated function declared earlier; this is also extremely useful in some other scenarios).
@psalm-github-bot
Copy link

I found these snippets:

https://psalm.dev/r/7be6130bcb
<?php
/**
 * @template A
 * @param A $a
 * @return A
 */
function identity($a) { return $a; }

/**
 * @template A
 * @return (callable(A): A)
 */
function makeIdentity(): callable { return 'identity'; }

/** @psalm-trace $a */
$a = identity('a');

/** @psalm-trace $identity */
$identity = makeIdentity();

/** @psalm-trace $b */
$b = $identity('b');
Psalm output (using commit 3ce41d7):

INFO: Trace - 16:1 - $a: "a"

INFO: Trace - 19:1 - $identity: callable(empty):empty

ERROR: InvalidScalarArgument - 22:16 - Argument 1 expects empty, "b" provided

INFO: Trace - 22:1 - $b: empty

INFO: UnusedVariable - 16:1 - $a is never referenced or the value is not used

INFO: UnusedVariable - 22:1 - $b is never referenced or the value is not used

@weirdan
Copy link
Collaborator

weirdan commented Mar 30, 2021

Or get it into the actual type, e.g. callable<T of mixed>(T):T

@klimick
Copy link
Contributor

klimick commented May 25, 2021

Related to #5581 #4589 #4550

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

No branches or pull requests

4 participants