psalm icon indicating copy to clipboard operation
psalm copied to clipboard

Allow importing type aliases on methods/functions

Open weirdan opened this issue 4 years ago • 5 comments

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

weirdan avatar Dec 08 '20 14:12 weirdan

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

psalm-github-bot[bot] avatar Dec 08 '20 14:12 psalm-github-bot[bot]

I think it could be related to #4290, it's not even possibile to use them with templates for classes.

thomasvargiu avatar Jan 14 '21 11:01 thomasvargiu

Also related to https://github.com/vimeo/psalm/issues/3511

louisreingold avatar Jan 19 '21 23:01 louisreingold

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.

rzvc avatar May 12 '22 20:05 rzvc

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
{
    // ...
}

jwdunne avatar Sep 08 '22 17:09 jwdunne