Error Identifier: return.unusedType
Every error reported by PHPStan has an error identifier. Here’s a list of all error identifiers. In PHPStan Pro you can see the error identifier next to each error and filter errors by their identifiers.
Code example #
<?php declare(strict_types = 1);
function doFoo(int $i): int|string
{
if ($i > 0) {
return $i;
}
return $i * -1;
}
Why is it reported? #
The declared return type contains a union type member that is never actually returned by the function or method. In the example above, the function declares int|string as its return type, but every code path returns an int value. The string part of the union is unused and makes the type declaration wider than necessary.
A too-wide return type reduces the type information available to callers, potentially forcing them to add unnecessary type checks.
How to fix it #
Narrow the return type by removing the type that is never returned:
<?php declare(strict_types = 1);
-function doFoo(int $i): int|string
+function doFoo(int $i): int
{
if ($i > 0) {
return $i;
}
return $i * -1;
}
If the broader return type is intentional because the function may return the other type in the future or in subclass overrides, consider keeping the type and reviewing whether the implementation is complete.
How to ignore this error #
You can use the identifier return.unusedType to ignore this error using a comment:
// @phpstan-ignore return.unusedType
codeThatProducesTheError();
You can also use only the identifier key to ignore all errors of the same type in your configuration file in the ignoreErrors parameter:
parameters:
ignoreErrors:
-
identifier: return.unusedType
Rules that report this error #
- PHPStan\Rules\TooWideTypehints\TooWideArrowFunctionReturnTypehintRule [1] [2]
- PHPStan\Rules\TooWideTypehints\TooWideClosureReturnTypehintRule [1] [2]
- PHPStan\Rules\TooWideTypehints\TooWideFunctionParameterOutTypeRule [1] [2]
- PHPStan\Rules\TooWideTypehints\TooWideFunctionReturnTypehintRule [1] [2]
- PHPStan\Rules\TooWideTypehints\TooWideMethodParameterOutTypeRule [1] [2]
- PHPStan\Rules\TooWideTypehints\TooWideMethodReturnTypehintRule [1] [2]
- PHPStan\Rules\TooWideTypehints\TooWidePropertyTypeRule [1] [2]