Skip to content

[Feature Request]: allow type aliases to be imported from non-class files #13315

Done
phpstan/phpstan-src
#7295

Description

@NickSdot

Feature request

Based on this problem I open this feature request as requested here. Initially I reported the following usage, which I expected to work:

/** @phpstan-type PassThroughArray array<string, string|array<array-key, mixed>> */
final class View
{
    /** @param PassThroughArray $passThrough  */
    public function __construct(
        public array $passThrough = [],
    ) {}
}

// functions.php

/**
 * @phpstan-import-type PassThroughArray from View
 * @param PassThroughArray $data
 */
function view(array $data): View
{
    return new View($data);
}

It, however, does not. Currently, imports can only be done from above a class. This unfortunatly disqualifies the usage of type aliases outside of classes.

I don't have a strong preference on how this should work, as long as it does I'd be happy. Here are some ideas I think could be helpful in general:

// 1️⃣ import from function docs

/**
 * @phpstan-import-type PassThroughArray from View
 * @param PassThroughArray $data
 */
function view(array $data): View {}

// 2️⃣ import from under non-class namespace(s)

namespace SomethingOne

/** 
 * @phpstan-import-type PassThroughArray from View
 */

// functions here

namespace SomethingTwo

/** 
 * @phpstan-import-typeBlub from View $data
 */

// functions here


// 3️⃣ extra: import from docs shorthand

/** @param PassThroughArray from View $data */
function view(array $data): View {}

Perhaps, 1️⃣ and 3️⃣ could also be interesting for classes.

Did PHPStan help you today? Did it make you happy in any way?

It always helps! Thanks for your hard work! ❤️

Activity

  1. ondrejmirtes commented on Dec 3, 2026

    @ondrejmirtes
    Member

    Declaring and importing type aliases is now possible thanks to phpstan/phpstan-src#7295.

    Also added support for generic aliases (@phpstan-type Foo<T> = array{a: T}) and recursive aliases (@phpstan-type Nested = array<string, string|Nested>) recently.

  2. NickSdot commented on Dec 3, 2026

    @NickSdot
    Author

    Thanks Ondrej!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions