-
Notifications
You must be signed in to change notification settings - Fork 669
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
Comments
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);
|
Inference has its limits, and there are time when you need to specify the type manually, e.g. https://psalm.dev/r/3b5cc796c1 |
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);
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In this example psalm.dev/r/6dbda66dde, I want the both
TKey
andTValue
to be anint
and not specific integers. How can I make this happen?The text was updated successfully, but these errors were encountered: