Skip to content

Commit ce5620c

Browse files
committed
Enhance inline @var documentation and add support for direct return statement type assertions
1 parent 20d0ee5 commit ce5620c

1 file changed

Lines changed: 30 additions & 3 deletions

File tree

docs/core-concepts/inline-variables.md

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Inline Variables (`@var`)
22

3-
While parameter and return contracts protect function boundaries, inline `@var` annotations enforce type safety on local variable assignments and reassignments inside function bodies or php file execution lines.
3+
While parameter and return contracts protect function boundaries, inline `@var` annotations enforce type safety on local variable assignments, reassignments, and direct return statements inside function bodies or PHP scripts.
44

55
---
66

@@ -43,7 +43,7 @@ TypePHP supports both single-variable single-line docblocks and multi-variable d
4343
$id = 100;
4444

4545
/** @var non-empty-string $name -> single-line docblock */
46-
$name = 'Reymart'
46+
$name = 'Reymart';
4747
```
4848

4949
### Multi-Variable Annotation (Array Destructuring)
@@ -79,6 +79,33 @@ Both `/** @var positive-int $count */` and `/** @var positive-int */` behave ide
7979

8080
---
8181

82+
## Inline `@var` on Direct Return Statements
83+
84+
You can place `/** @var Type */` directly above a `return` statement to perform surgical, expression-level type assertion narrowing inside function bodies, closures, or specific conditional branches:
85+
86+
```php
87+
function fetchUserScores(): array
88+
{
89+
/** @var list<positive-int> */
90+
return [10, 20, 30]; // Valid
91+
}
92+
93+
function fetchBadScores(): array
94+
{
95+
/** @var list<positive-int> */
96+
return [10, -5, 30]; // Throws TypeError on -5!
97+
}
98+
99+
$getUser = function () use ($repo) {
100+
/** @var array{id: positive-int, username: non-empty-string} */
101+
return $repo->fetchRawUser();
102+
};
103+
```
104+
105+
> **PHPStan & Psalm Parity:** Static analysis tools treat `/** @var Type */ return $expr;` as an inline type cast assertion. TypePHP physically enforces this assertion at runtime, ensuring that live dynamic returns strictly satisfy the annotated type.
106+
107+
---
108+
82109
## Block-Level Scope Isolation & Shadowing
83110

84111
TypePHP tracks variable type contracts using **Lexical Block Scope Frames**.
@@ -146,4 +173,4 @@ You can enable or disable specific categories of inline variable validation in `
146173
'arrays' => true, // Array shapes and lists (array{id: int}, list<T>)
147174
'objects' => true, // Class instance checks (@var User $user)
148175
],
149-
```
176+
```

0 commit comments

Comments
 (0)