diff --git a/composer.json b/composer.json index 9ec72d60..c641c0c5 100644 --- a/composer.json +++ b/composer.json @@ -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" }, diff --git a/src/Support/TypeScriptTransformer/DataTypeScriptTransformer.php b/src/Support/TypeScriptTransformer/DataTypeScriptTransformer.php index 81bf5ce8..66cdff01 100644 --- a/src/Support/TypeScriptTransformer/DataTypeScriptTransformer.php +++ b/src/Support/TypeScriptTransformer/DataTypeScriptTransformer.php @@ -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(), ); diff --git a/tests/Support/TypeScriptTransformer/DataTypeScriptTransformerTest.php b/tests/Support/TypeScriptTransformer/DataTypeScriptTransformerTest.php index 8988300c..7515401a 100644 --- a/tests/Support/TypeScriptTransformer/DataTypeScriptTransformerTest.php +++ b/tests/Support/TypeScriptTransformer/DataTypeScriptTransformerTest.php @@ -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); +}); diff --git a/tests/__snapshots__/DataTypeScriptTransformerTest__it_supports_converting_nullable_types_to_optional_properties__1.txt b/tests/__snapshots__/DataTypeScriptTransformerTest__it_supports_converting_nullable_types_to_optional_properties__1.txt new file mode 100644 index 00000000..c18ab661 --- /dev/null +++ b/tests/__snapshots__/DataTypeScriptTransformerTest__it_supports_converting_nullable_types_to_optional_properties__1.txt @@ -0,0 +1,3 @@ +{ +nullable?: string; +} \ No newline at end of file