psalm
psalm copied to clipboard
Allow importing type aliases on methods/functions
Currently Psalm processes @psalm-import-type
in docblocks of classlikes only. It would be useful to be able to import types in function docblocks as well.
https://psalm.dev/r/138af4f19d Expected: no issues
I found these snippets:
https://psalm.dev/r/138af4f19d
<?php
namespace A {
/** @psalm-type _AType=int|string */
final class Types {}
}
namespace B {
use A\Types;
/**
* @psalm-import-type _AType from Types as _Q
* @param _Q $p
*/
function f($p): void {}
class C {
/**
* @psalm-import-type _AType from Types as _Z
* @param _Z $p
*/
public function f($p): void {}
}
}
Psalm output (using commit 91ee4ae):
ERROR: UndefinedDocblockClass - 10:15 - Docblock-defined class or interface B\_Q does not exist
ERROR: UndefinedDocblockClass - 17:18 - Docblock-defined class or interface B\_Z does not exist
I think it could be related to #4290, it's not even possibile to use them with templates for classes.
Also related to https://github.com/vimeo/psalm/issues/3511
Is there any workaround for this?
@psalm-type
seems to be a very powerful utility, but it suffers from a couple of crippling limitations. The one in this issue being one of them.
Is there any workaround for this?
@psalm-type
seems to be a very powerful utility, but it suffers from a couple of crippling limitations. The one in this issue being one of them.
For functions, there is a not-very-elegant work around. Given a file of functions, it's possible to declare an empty, throwaway class at the top where you can import types, which can then be used by any other functions in the file. Example:
/**
* @psalm-import-type Type from Types
*/
class ImportedTypes
{
}
/**
* @param Generator<int, Type> $xs
* @return Generator<int, Type>
*/
function something(Generator $xs): Generator
{
// ...
}