Skip to content

Support assertNever pattern for exhaustive checks #9133

@JanTvrdik

Description

@JanTvrdik

PHPStan currently does not emit error when you pass non-never value to a parameter that requires never.

/** @param never $value */
function assertNever(mixed $value): never
{
    throw new LogicException();
}

assertNever(123); // this should return error because 123 is not subtype of never

Use Case: exhaustive checks

This is commonly used for implementation of typesafe exhaustive checks in TypeScript. It is especially useful when dealing with enums, sealed classes or union types.

function testMissingCheck(int|string $value): void
{
    if (is_string($value)) {
        echo 'STRING';
    } else {
        assertNever($value); // this should return error, because int is not a subtype of never
    }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions