Psalm: Inheritance and generic types

Created on 6 Nov 2018  Â·  7Comments  Â·  Source: vimeo/psalm

Would it be possible to add an annotation to "expand" the definition of extends?

/**
 * @template T
 */
class Database
{
    ...
}

/**
 * @extends Database<mysqli>
 */ 
class MySQLDatabase extends Database
{
}

The annotation should make alias T = mysqli for all inherited methods, when in scope of MySQLDatabase.

enhancement

Most helpful comment

I've added support for @template-extends and @template-implements annotations. They're mainly designed for one templated class to extend another templated class, but it should also work for your use case.

There's still a lack of validation - https://getpsalm.org/r/f305083fea, for example, should be an error but currently isn't.

All 7 comments

There's (non-working, but present) @template-extends annotation: https://github.com/vimeo/psalm/blob/6cf6d2cfda34da038e5cb9015a9f77221cb1a2ed/src/Psalm/Stubs/CoreGenericClasses.php#L20

Right now it has no effect at all, but I'd like to see it working.

I'd like to see it working.

I am interested in getting this work. Can you provide me with some approximate plan of how the solution might look like? Which classes/method should I be looking at?

I also think there's a need for an extra annotation in order to deal with traits. Here's just one example how confusing and convoluted the automatic type deduction can be: https://getpsalm.org/r/6bcf6f2607

The best I can think of is a @template-use annotation that can be added on top of use statement to explicitly alias all the types used in traits.

/**
 * @template-use CollectionTrait<int>
 */
use CollectionTrait;

I also think there's a need for an extra annotation in order to deal with traits

Yeah, that's a definite bug - would you mind filing in a separate ticket? No easy solution, but it's not the same situation as this ticket

I've added support for @template-extends and @template-implements annotations. They're mainly designed for one templated class to extend another templated class, but it should also work for your use case.

There's still a lack of validation - https://getpsalm.org/r/f305083fea, for example, should be an error but currently isn't.

The above is now an error ERROR: ImplementedReturnTypeMismatch - 29:16 - The return type 'A\Bar' for A\Container::getItem is different to the implemented return type for A\FooContainer::getitem 'A\Foo'

Would it be possible to spell out generic params as well? Like The return type 'A\Bar' for A\Container<Bar>::getItem …

Was this page helpful?
0 / 5 - 0 ratings

Related issues

vudaltsov picture vudaltsov  Â·  3Comments

Ocramius picture Ocramius  Â·  3Comments

roukmoute picture roukmoute  Â·  3Comments

greg0ire picture greg0ire  Â·  3Comments

weirdan picture weirdan  Â·  4Comments