Skip to content

PHPStan generic arguments not working #538

@mindplay-dk

Description

@mindplay-dk

The generics by example article on phpstan.org includes the following example of generic return types:

class Container
{
	/**
	 * @template T of object
	 * @return ($name is class-string<T> ? T : object)
	 */
	public function get(string $name): object
	{
		// ...
	}
}

This doesn't work as expected.

Here is an example with the types reported by PHPStan:

<?php

class Container
{
	/**
	 * @template T of object
	 * @param string $name component name
	 * @return ($name is class-string<T> ? T : mixed)
	 */
	public function get(string $name): mixed
	{
		// ...
	}
}

class MyService {}

function hello(NotMyService $service) {
	// ...
}

$c = new Container();

$service = $c->get(MyService::class);

\PHPStan\dumpType($service); // 👈 MyService 👍

$stuff = $c->get("stuff");

\PHPStan\dumpType($stuff); // 👈 mixed 👍

The same example returns different hover types (and type-checks) with your extension:

$service = $c->get(MyService::class); // 👈 mixed|T 👎

$stuff = $c->get("stuff"); // 👈 mixed|T 👎

Is there any particular reason you're inventing your own type inference and type-checking in you product?

PHPStan is open source and MIT licensed and extremely good at inference and type-checking. 🙂

Metadata

Metadata

Assignees

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