Thanks to the typescript-transformer package, you can automatically transform data objects into TypeScript definitions.
This PHP data object:
class DataObject extends Data
{
public function __construct(
public null|int $nullable,
public int $int,
public bool $bool,
public string $string,
public float $float,
/** @var string[] */
public array $array,
public Lazy|string $lazy,
public Optional|string $optional,
public SimpleData $simpleData,
/** @var \Spatie\LaravelData\Tests\Fakes\SimpleData[] */
public DataCollection $dataCollection,
)
{
}
}
Transforms to this TypeScript type:
{
nullable: number | null;
int: number;
bool: boolean;
string: string;
float: number;
array: Array<string>;
lazy? : string;
optional? : string;
simpleData: SimpleData;
dataCollection: Array<SimpleData>;
}
Installation
Install the TypeScript transformer package:
composer require spatie/laravel-typescript-transformer
Publish the config file:
php artisan vendor:publish --tag=typescript-transformer-config
Add the transformer to typescript-transformer.php:
'transformers' => [
Spatie\LaravelData\Support\TypeScriptTransformer\DataTypeScriptTransformer::class,
// Other transformers...
],
If you’re using the DtoTransformer provided by the package, put the DataTypeScriptTransformer before it.
Usage
Annotate data objects you want to transform:
/** @typescript */
class SongData extends Data
{
// ...
}
Or use the attribute:
use Spatie\TypeScriptTransformer\Attributes\TypeScript;
#[TypeScript]
class SongData extends Data
{
// ...
}
Generate TypeScript definitions:
php artisan typescript:transform
Use the DataTypeScriptCollector to automatically transform all data objects:
In typescript-transformer.php:
'collectors' => [
Spatie\LaravelData\Support\TypeScriptTransformer\DataTypeScriptCollector::class,
// Other collectors...
],
If you’re using the DefaultCollector, put the DataTypeScriptCollector before it.
Optional Types
Lazy and optional properties become optional in TypeScript:
class DataObject extends Data
{
public function __construct(
public Lazy|string $lazy,
public Optional|string $optional,
)
{
}
}
Transforms to:
{
lazy? : string;
optional? : string;
}
Optional Without Lazy/Optional Types
Use the Optional attribute from typescript-transformer:
use Spatie\TypeScriptTransformer\Attributes\Optional as TypeScriptOptional;
class DataObject extends Data
{
public function __construct(
#[TypeScriptOptional]
public int $id,
public string $someString,
public Optional|string $optional,
)
{
}
}
Alias the TypeScript Optional attribute to avoid conflicts with Laravel Data’s Optional type.