Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inferring the type of intersection #10924

Closed
darkdarin opened this issue Apr 28, 2024 · 2 comments
Closed

Inferring the type of intersection #10924

darkdarin opened this issue Apr 28, 2024 · 2 comments

Comments

@darkdarin
Copy link

darkdarin commented Apr 28, 2024

I'm writing classes to represent various types in PHP.
Example: https://psalm.dev/r/7c9c4882a9

I get the inferred type:
INFO: [Trace](https://psalm.dev/224) - 34:1 - $types: IntersectType<Countable|Traversable>

Its correct for Union Type represent, but I want to represent Intersect type and to get inferred type IntersectType<Countable&Traversable>.
What should I do for this?

Copy link

I found these snippets:

https://psalm.dev/r/7c9c4882a9
<?php

/**
 * @template-covariant TType
 * @psalm-immutable
 */
interface TypeInterface {}

/**
 * @template TClass
 * @implements TypeInterface<TClass>
 * @psalm-immutable
 */
class ClassType implements TypeInterface 
{
    /** @param class-string<TClass> $className */
	public function __construct(public string $className){}
}

/**
 * @template-covariant TIntersectType
 * @implements TypeInterface<TIntersectType>
 * @psalm-immutable
 */
class IntersectType implements TypeInterface 
{
    /**
     * @param TypeInterface<TIntersectType> ...$types
     */
	public function __construct(public TypeInterface ...$types) {}
}

/** @psalm-trace $types */
$types = new IntersectType(
    new ClassType(\Traversable::class), 
    new ClassType(\Countable::class),
);

return $types;
Psalm output (using commit 08afc45):

INFO: Trace - 34:1 - $types: IntersectType<Countable|Traversable>

@danog
Copy link
Collaborator

danog commented May 13, 2024

This is actually correct, as fetching $type->types[$idx] will return either Countable OR a Traversable, depending on the index.

@danog danog closed this as completed May 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants