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

Binding scalars to generics #3769

Closed
MidnightDesign opened this issue Aug 24, 2020 · 5 comments
Closed

Binding scalars to generics #3769

MidnightDesign opened this issue Aug 24, 2020 · 5 comments

Comments

@MidnightDesign
Copy link
Contributor

It would be great if generics supported binding scalars. Here's a use case:

/**
 * @template K of array-key
 * @param array<K, int> $in
 * @return array<K, string>
 */
function stringValues(array $in): array {
    return array_map(fn (int $int): string => (string) $int, $in);
}

Currently, this gives me a

PHPDoc tag @template K for function stringValues() with bound type (int|string) is not supported.

See https://phpstan.org/r/f80b7892-415f-4c38-a63b-37b885d1b6ae

I have read somewhere that this is being considered, but I couldn't find an issue for it and I wanted to provide a use case.

@ondrejmirtes
Copy link
Member

I'm kind of undecided if the K in case of a literal value like 1 should be resolved to int or 1. Currently (if you don't use the bound) 1 is resolved to int. So for example passing 1 as T and returning array<T> leads to array<int>.

@ondrejmirtes ondrejmirtes added this to the Generics milestone Aug 24, 2020
@MidnightDesign
Copy link
Contributor Author

In TypeScript, literals in code are generalized: const num = 1; // type 'number'.
But literals in types are not: type oneOrTwo = 1 | 2; const num = 1 as oneOrTwo; // type '1 | 2'.

Since we're dealing with types here, I'd say they should not be generalized.

Don't know if this helps though. Or if that's even what you meant.

@simPod
Copy link
Contributor

simPod commented Feb 7, 2021

psalm has support for it. Would be nice if both tools interpreted this in the same way.

@ondrejmirtes
Copy link
Member

Implemented: phpstan/phpstan-src@ac7b49e

@github-actions
Copy link

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Apr 29, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants