Menu

← Back to generics.*

Error Identifier: generics.requiredTypeAfterOptional

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);

/**
 * @template T = string
 * @template U
 */
class Container
{
}

Why is it reported? #

A required @template type parameter appears after an optional one. Template type T has a default value (= string), making it optional, but the subsequent template type U does not have a default value, making it required. Just like function parameters, required template types must come before optional ones.

When a generic type is instantiated, type arguments are assigned in order. If an optional template parameter precedes a required one, it becomes impossible to omit the optional argument while still providing the required one.

How to fix it #

Reorder the template parameters so that all required types come before optional ones:

 <?php declare(strict_types = 1);
 
 /**
- * @template T = string
  * @template U
+ * @template T = string
  */
 class Container
 {
 }

Alternatively, give the required template type a default value as well:

 <?php declare(strict_types = 1);
 
 /**
  * @template T = string
- * @template U
+ * @template U = int
  */
 class Container
 {
 }

How to ignore this error #

You can use the identifier generics.requiredTypeAfterOptional to ignore this error using a comment:

// @phpstan-ignore generics.requiredTypeAfterOptional
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: generics.requiredTypeAfterOptional

Rules that report this error #

  • PHPStan\Rules\Generics\ClassTemplateTypeRule [1]
  • PHPStan\Rules\Generics\FunctionTemplateTypeRule [1]
  • PHPStan\Rules\Generics\InterfaceTemplateTypeRule [1]
  • PHPStan\Rules\Generics\MethodTagTemplateTypeRule [1]
  • PHPStan\Rules\Generics\MethodTagTemplateTypeTraitRule [1]
  • PHPStan\Rules\Generics\MethodTemplateTypeRule [1]
  • PHPStan\Rules\Generics\TraitTemplateTypeRule [1]
  • PHPStan\Rules\PhpDoc\IncompatiblePhpDocTypeRule [1]
  • PHPStan\Rules\PhpDoc\IncompatiblePropertyHookPhpDocTypeRule [1]
  • PHPStan\Rules\PhpDoc\IncompatiblePropertyPhpDocTypeRule [1]

Edit this page on GitHub

Theme
A
© 2026 PHPStan s.r.o.