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

PropertyTypeCoercion when constructing WeakMap #7131

Closed
dvdoug opened this issue Dec 11, 2021 · 6 comments
Closed

PropertyTypeCoercion when constructing WeakMap #7131

dvdoug opened this issue Dec 11, 2021 · 6 comments

Comments

@dvdoug
Copy link

dvdoug commented Dec 11, 2021

When initialising an (appropriately annotated) property that is a WeakMap, Psalm complains about type coercion when calling the constructor. There cannot be any possibility of type coercion at that point, the newly constructed map is empty.

Reproducer: https://psalm.dev/r/b3a63077ef

Potentially a variation of #4055 ?

@psalm-github-bot
Copy link

I found these snippets:

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

declare(strict_types=1);

use WeakMap;

class Foo
{
    /** @var WeakMap<SplFileObject, int> */
    protected WeakMap $bar;

    public function __construct()
    {
            $this->bar = new WeakMap();
    }
}
Psalm output (using commit 858be40):

ERROR: PropertyTypeCoercion - 14:26 - $this->bar expects 'WeakMap<SplFileObject, int>',  parent type 'WeakMap<object, mixed>' provided

@weirdan
Copy link
Collaborator

weirdan commented Dec 11, 2021

At this point this is well-known limitation of Psalm generics. To work around this you have to provide the type information missing at the generic construction point using @var: https://psalm.dev/r/a0a3590bcd

@weirdan weirdan closed this as completed Dec 11, 2021
@psalm-github-bot
Copy link

I found these snippets:

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

declare(strict_types=1);

use WeakMap;

class Foo
{
    /** @var WeakMap<SplFileObject, int> */
    protected WeakMap $bar;

    public function __construct()
    {
        /** @var WeakMap<SplFileObject, int> */
        $this->bar = new WeakMap();
    }
}
Psalm output (using commit f79f857):

No issues!

@dvdoug
Copy link
Author

dvdoug commented Dec 12, 2021

Hi

You say "well-known" but I wasn't able to find anything in the docs when I looked or in the existing issues list. Is there a link where I can find out more?

@bwoebi
Copy link

bwoebi commented Feb 6, 2024

Hey @weirdan,

I just encountered that same issue, is there any reason it cannot be initialized the same way than SplObjectStorage is, similarly to 346d475?

@danog
Copy link
Collaborator

danog commented Feb 6, 2024

I've started working on #10577 to fix this.

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

5 participants