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

Conditional types by enum not working #11033

Open
WalterWoshid opened this issue May 15, 2024 · 0 comments
Open

Conditional types by enum not working #11033

WalterWoshid opened this issue May 15, 2024 · 0 comments

Comments

@WalterWoshid
Copy link

WalterWoshid commented May 15, 2024

Bug report

Example:

/**
 * @phpstan-template T of GotoTarget
 *
 * @phpstan-type CandidateNotesData array{candidate: string, note: string}
 * @phpstan-type PersonalmanagerData array{token: string}
 *
 * @phpstan-type GotoRouteDataTypes array{
 *     'personalmanager': PersonalmanagerData,
 *     'my-pending-reviews': null,
 *     'candidate-notes': CandidateNotesData,
 *     'dashboard': null,
 * }
 *      ↑
 *      Would also be nice if you could use Enums as the key for arrays.
 */
final class GotoRoute
{
    /**
     * @phpstan-var T
     */
    public GotoTarget $target;

    /**
     * @phpstan-var GotoRouteDataTypes[value-of<T>]
     */
    public ?array $data = null;
}

enum GotoTarget: string
{
    case PERSONALMANAGER = 'personalmanager';
    case MY_PENDING_REVIEWS = 'my-pending-reviews';
    case CANDIDATE_NOTES = 'candidate-notes';
    case DASHBOARD = 'dashboard';
}

PhpStan complains for this line: public ?array $data = null; with

phpstan: PHPDoc tag @var for property GotoRoute::$data with type array{personalmanager: array{token: string}, my-pending-reviews: null, candidate-notes: array{candidate: string, note: string}, dashboard: null}[value-of<T>] is not subtype of native type array|null.

and

phpstan: Property GotoRoute::$data type has no value type specified in iterable type array.

What I want to achieve is the following:

  • T ($target) is GotoTarget::DASHBOARD -> $data is null
  • T ($target) is GotoTarget::PERSONALMANAGER -> $data is array{token: string}

It works with this:

/**
 * @phpstan-var (T is GotoTarget::PERSONALMANAGER ? PersonalmanagerData : (T is GotoTarget::CANDIDATE_NOTES ? CandidateNotesData : null))
 */
public ?array $data = null;

But I don't like it, because the more you add, the uglier it gets.

Code snippet that reproduces the problem

https://phpstan.org/r/7fa9183e-5190-4c79-a545-40e40be1033c

Expected output

  • T ($target) is GotoTarget::DASHBOARD -> $data is null
  • T ($target) is GotoTarget::PERSONALMANAGER -> $data is array{token: string}
@ondrejmirtes ondrejmirtes added this to the Generics milestone May 30, 2024
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

2 participants