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

Non-null template value #10903

Open
mj4444ru opened this issue Apr 11, 2024 · 1 comment
Open

Non-null template value #10903

mj4444ru opened this issue Apr 11, 2024 · 1 comment

Comments

@mj4444ru
Copy link

Hello. How can I tell psalm in this example that the functions getNotNullValue and getNotNullValue2 return type T, but the result cannot be a null value?

Thank you.

https://psalm.dev/r/80529364ec

Copy link

I found these snippets:

https://psalm.dev/r/80529364ec
<?php

interface TestInterface
{
    function test(): void;
}

/**
 * @template T of TestInterface|null
 */
class Test
{
    /**
     * @psalm-param T $value
     */
    public function __construct(
        public TestInterface|null $value
    ) {
    }
    
    /**
     * @return T
     */
    public function getValue(): ?TestInterface
    {
        return $this->value;
    }

    /**
     * @return (T is null ? TestInterface : T)
     */
    public function getNotNullValue(): TestInterface
    {
        if ($this->value === null) {
            throw new Exception('Error');
        }
        
        return $this->value;
    }

    /**
     * @return (T is null ? TestInterface : T)
     */
    public function getNotNullValue2(): TestInterface
    {
        return $this->value ?? throw new Exception('Error');
    }
    
    public function test(): void
    {
        $notNullValue = $this->getNotNullValue();
        /** @psalm-trace $notNullValue */
        $notNullValue->test();
    }
}
Psalm output (using commit ef3b018):

ERROR: PossiblyNullReference - 53:24 - Cannot call method test on possibly null value

INFO: Trace - 53:9 - $notNullValue: (T:Test as TestInterface|null)|TestInterface

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

1 participant