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

How to infer type from generics #6357

Closed
nunomaduro opened this issue Aug 23, 2021 · 3 comments
Closed

How to infer type from generics #6357

nunomaduro opened this issue Aug 23, 2021 · 3 comments

Comments

@nunomaduro
Copy link

nunomaduro commented Aug 23, 2021

In this example psalm.dev/r/6dbda66dde, I want the both TKey and TValue to be an int and not specific integers. How can I make this happen?

@psalm-github-bot
Copy link

I found these snippets:

https://psalm.dev/r/6dbda66dde
<?php 

/**
 * @template TKey of array-key
 * @template TValue
 */
class Collection {
    /**
     * @var array<TKey, TValue>
     */
    protected $items = [];
	
	/**
     * Create a new collection.
     *
     * @param  array<TKey, TValue>  $items
     * @return void
     */
    public function __construct($items)
    {
        $this->items = $items;
    }
	
    /**
     * Add an item to the collection.
     *
     * @param  TKey  $key
     * @param  TValue  $item
     * @return $this
     */
    public function add($key, $item)
    {
        $this->items[$key] = $item;

        return $this;
    }
}

(new Collection([1, 2]))->add(2, 3);
Psalm output (using commit 9222b24):

ERROR: InvalidArgument - 39:31 - Argument 1 of Collection::add expects 0|1, 2 provided

ERROR: InvalidArgument - 39:34 - Argument 2 of Collection::add expects 1|2, 3 provided

@weirdan
Copy link
Collaborator

weirdan commented Aug 23, 2021

Inference has its limits, and there are time when you need to specify the type manually, e.g. https://psalm.dev/r/3b5cc796c1

@weirdan weirdan closed this as completed Aug 23, 2021
@psalm-github-bot
Copy link

I found these snippets:

https://psalm.dev/r/3b5cc796c1
<?php 

/**
 * @template TKey of array-key
 * @template TValue
 */
class Collection {
    /**
     * @var array<TKey, TValue>
     */
    protected $items = [];
	
	/**
     * Create a new collection.
     *
     * @param  array<TKey, TValue>  $items
     * @return void
     */
    public function __construct($items)
    {
        $this->items = $items;
    }
	
    /**
     * Add an item to the collection.
     *
     * @param  TKey  $key
     * @param  TValue  $item
     * @return $this
     */
    public function add($key, $item)
    {
        $this->items[$key] = $item;

        return $this;
    }
}

/** @var Collection<int, int> */
$c = new Collection([1, 2]);

$c->add(2, 3);
Psalm output (using commit 9222b24):

No issues!

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