Skip to content

Commit

Permalink
feat: support "null to optional" (#881)
Browse files Browse the repository at this point in the history
* feat: support "null to optional"

* chore: bump minimum version of `spatie/laravel-typescript-transformer`
  • Loading branch information
innocenzi authored Oct 22, 2024
1 parent 6e2d28d commit e409a5b
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 2 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
"phpstan/extension-installer": "^1.1",
"phpunit/phpunit": "^10.0",
"spatie/invade": "^1.0",
"spatie/laravel-typescript-transformer": "^2.3",
"spatie/laravel-typescript-transformer": "^2.5",
"spatie/pest-plugin-snapshots": "^2.1",
"spatie/test-time": "^1.2"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,13 @@ function (string $carry, ReflectionProperty $property) use ($isOptional, $dataCl
fn (object $attribute) => $attribute instanceof TypeScriptOptional
)
|| ($dataProperty->type->lazyType && $dataProperty->type->lazyType !== ClosureLazy::class)
|| $dataProperty->type->isOptional;
|| $dataProperty->type->isOptional
|| ($dataProperty->type->isNullable && $this->config->shouldConsiderNullAsOptional());

$transformed = $this->typeToTypeScript(
$type,
$missingSymbols,
$this->config->shouldConsiderNullAsOptional(),
currentClass: $property->getDeclaringClass()->getName(),
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -322,3 +322,21 @@ public function __construct(
$transformer->transform($reflection, 'DataObject')->transformed
);
});

it('supports converting nullable types to optional properties', function () {
$config = TypeScriptTransformerConfig::create();
$config->nullToOptional(true);

$data = new class ('foo') extends Data {
public function __construct(
public ?string $nullable,
) {
}
};

$transformer = new DataTypeScriptTransformer($config);
$reflection = new ReflectionClass($data);

expect($transformer->canTransform($reflection))->toBeTrue();
assertMatchesSnapshot($transformer->transform($reflection, 'DataObject')->transformed);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
nullable?: string;
}

0 comments on commit e409a5b

Please sign in to comment.