Skip to content

Commit 647b117

Browse files
committed
Appended properties can be typed if they're typed in the docstring
1 parent 8634f6f commit 647b117

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed

src/ModelTransformer.php

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,19 @@ public function transform(ReflectionClass $class, string $name): TransformedType
5151
}
5252

5353
foreach ($appends as $append) {
54-
$typescriptProperties[] = "$append: any";
54+
$type = 'any';
55+
if ($comment = $class->getDocComment()) {
56+
$matches = [];
57+
$regex = '/@property\s+([^\s]+)\s+\$' . $append . '\s*\n/';
58+
59+
preg_match($regex, $comment, $matches);
60+
61+
if (count($matches) > 1) {
62+
$type = $this->mapCastToType($matches[1]);
63+
}
64+
}
65+
66+
$typescriptProperties[] = "$append: $type";
5567
}
5668

5769
return TransformedType::create(

tests/Feature/TransformEloquentModelsTest.php

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,14 +140,38 @@
140140
$table->id();
141141
});
142142

143+
/**
144+
* @property string $appended_attribute_str
145+
* @property int $appended_attribute_int
146+
*/
143147
$model = new class extends \Illuminate\Database\Eloquent\Model {
144148
protected $table = 'test_table';
145-
protected $appends = ['appended_attribute'];
149+
protected $appends = [
150+
'appended_attribute',
151+
'appended_attribute_str',
152+
'appended_attribute_array',
153+
'appended_attribute_int',
154+
];
146155

147156
public function appendedAttribute()
148157
{
149158
new Attribute(get: fn() => 'some value');
150159
}
160+
161+
public function appendedAttributeStr()
162+
{
163+
new Attribute(get: fn() => 'some value');
164+
}
165+
166+
public function appendedAttributeArray()
167+
{
168+
new Attribute(get: fn() => []);
169+
}
170+
171+
public function appendedAttributeInt()
172+
{
173+
new Attribute(get: fn() => 1);
174+
}
151175
};
152176

153177
$transformer = new ModelTransformer;
@@ -157,6 +181,9 @@ public function appendedAttribute()
157181
// Numbers
158182
"id: number\n" .
159183
"appended_attribute: any\n" .
184+
"appended_attribute_str: string\n" .
185+
"appended_attribute_array: any\n" .
186+
"appended_attribute_int: number\n" .
160187
'}';
161188

162189
expect($transformedType?->transformed)->toEqual($type_definition);

0 commit comments

Comments
 (0)