mirror of
https://github.com/danog/psalm.git
synced 2024-11-27 04:45:20 +01:00
docs: describe template support of properties-of<T>
This commit is contained in:
parent
be49037d70
commit
8ebc9b599f
@ -9,8 +9,8 @@ and their respective types as values. This can be useful if you need to convert
|
||||
|
||||
```php
|
||||
class A {
|
||||
public string $foo;
|
||||
public int $bar;
|
||||
public string $foo = 'foo!';
|
||||
public int $bar = 42;
|
||||
|
||||
/**
|
||||
* @return properties-of<self>
|
||||
@ -38,3 +38,32 @@ properties with a certain visibility:
|
||||
- `public-properties-of<T>`
|
||||
- `protected-properties-of<T>`
|
||||
- `private-properties-of<T>`
|
||||
|
||||
|
||||
### Limited template support
|
||||
|
||||
As there is no way to statically analyze if a method returns all properties of a generic param (e.g. via Reflection or
|
||||
serialization), you have to annotate it where you assume it.
|
||||
|
||||
```php
|
||||
/**
|
||||
* @param T $object
|
||||
* @return properties-of<T>
|
||||
*/
|
||||
public function asArray($object): array {
|
||||
/** @var properties-of<T> */
|
||||
$array = json_decode(json_encode($object), true);
|
||||
return $array;
|
||||
}
|
||||
|
||||
|
||||
class A {
|
||||
public string $foo = 'foo!';
|
||||
public int $bar = 42;
|
||||
}
|
||||
|
||||
$a = new A();
|
||||
$aAsArray = asArray($a);
|
||||
$aAsArray['foo']; // valid
|
||||
$aAsArray['adams']; // error!
|
||||
```
|
||||
|
Loading…
Reference in New Issue
Block a user