Skip to content

False positive InvalidReturnType for method that always throws #9604

Open
@derrabus

Description

Given the following code:

class Logger
{
    public static function logCall(string $method): void
    {
    }
}

abstract class MyAbstractClass
{    
    /**
     * @return string
     */
    public function doSomething()
    {
        Logger::logCall(__METHOD__);

        throw new Exception('Not supported.');
    }
}

https://psalm.dev/r/b8245d5f63

Psalm reports:

ERROR: InvalidReturnType - 13:16 - The declared return type 'string' for MyAbstractClass::doSomething is incorrect, got 'never'

I would argue that the return type is still correct, it's just that the return type inferred by Psalm is more specific. The problem here is that this method is overridden by child classes and those implementations actually return a string. If I would document @return never here, the child implementation would illegally widen the return type from never to string.

Note that the error goes away if I…

  • … set the native return type to string.
  • … remove the Logger::logCall(__METHOD__); line from the method.

Both should be pretty much irrelevant for the issue. 🤔

Activity

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

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions