psalm icon indicating copy to clipboard operation
psalm copied to clipboard

Recursive properties-of<Class> type

Open juacala opened this issue 11 months ago • 4 comments

We've made quite a lot of use in the properties-of<ClassName> methodology for dealing with array shapes. One issue we've ran into, is that if there is an array shape with an array shape inside of it, we're forced with making the property of ClassName an array shape. We'd like to create classes that references classes all the way down, so that eventually we can get rid of the array shapes altogether and just use the classes, but it's a little awkward right now.

Thoughts on adding something like properties-of-recursive<T> to psalm?

For example

/**
 * @psalm-type NestedType = array{
 *  nested: null|array{
 *   prop1: string
 *  }
 * }
 */

We'd like to represent as two classes

class NestedType
{
  public NestedInner|null $nested=null;
}

class NestedInner
{
  public string $prop1='';
}
/**
 * @psalm-type NestedType = properties-of-recursive<NestedType>
 */

juacala avatar Mar 01 '24 14:03 juacala

Hey @juacala, can you reproduce the issue on https://psalm.dev? These will be used as phpunit tests when implementing the feature or fixing this bug.

psalm-github-bot[bot] avatar Mar 01 '24 14:03 psalm-github-bot[bot]

This is really a feature request.

juacala avatar Mar 01 '24 14:03 juacala

And what is the code that produces values of that type? Is it some kind of serialization library?

weirdan avatar Mar 01 '24 14:03 weirdan

This is mainly JSON communication from a browser (client) to the server with nested structures, and it's currently being decoded into an array. It's a bit of a refactor to change it into using an object. These can be somewhat large, and deeply nested.

We'd like to type it using objects to make the transition smoother. We've also tried @psalm-type array{...} with the corresponding array shape, but the bigger those get, the more unwieldy they are. Also the properties-of<ClassName> works great with a lot of IDEs since they can resolve immediately to the class.

juacala avatar Mar 01 '24 16:03 juacala

@weirdan if you would be amenable to the addition, and can give some guidance on where to start, I'd be happy to get someone on my team to put together a pull request to get this working.

juacala avatar Mar 07 '24 16:03 juacala