Hybridly aims to provide typings whenever it's possible. While the core and the front-end adapters of Hybridly are written with TypeScript and always provide definitions, code from the back-end must still be transformed to types in order to benefit from autocompletion while staying DRY.
This could be a real challenge — fortunately, there are existing solutions to transform PHP classes and enums to TypeScript types and interfaces. Specifically, Hybridly provides back-end typings through Data and TypeScript Transformer.
Using the preset?
Note that if you scaffolded an application using the provided preset, you don't need to take the installation steps described in this page. However, it's still interesting knowing why they are needed.
Data provides an interface to create rich data objects that can be used in various ways — for instance, it can replace Form Requests or resources.
But most importantly, it allows us to generate TypeScript interfaces through the TypeScript Transformer package.
If you weren't using it before, you need to know that it's an essential part of building hybrid applications. You may install it using composer:
composer require spatie/laravel-data
Transforming PHP to TypeScript
Thanks to Spatie, it's very easy to generate TypeScript interfaces from data objects and enums. Start by installing TypeScript Transformer and publish its configuration file:
composer require spatie/laravel-typescript-transformer php artisan vendor:publish --tag=typescript-transformer-config
config/typescript-transformer.php and update the following properties:
'collectors' => [ Spatie\TypeScriptTransformer\Collectors\DefaultCollector::class, Hybridly\Support\TypeScriptTransformer\DataResourceTypeScriptCollector::class, Spatie\LaravelData\Support\TypeScriptTransformer\DataTypeScriptCollector::class, ], 'transformers' => [ Spatie\LaravelTypeScriptTransformer\Transformers\SpatieStateTransformer::class, Spatie\TypeScriptTransformer\Transformers\SpatieEnumTransformer::class, Spatie\TypeScriptTransformer\Transformers\DtoTransformer::class, Spatie\LaravelData\Support\TypeScriptTransformer\DataTypeScriptTransformer::class, Spatie\TypeScriptTransformer\Transformers\EnumTransformer::class, ],
The configuration above uses a collector provided by Hybridly that finds
DataResource objects and generates typings with their authorizations. This is what powers typed authorization support.
It also configures the collector and transformer from
laravel-data to transform data objects, as well as the
EnumTransformer that is not, for some reason, configured by default.
Note that Hybridly automatically runs
php artisan typescript:generate through
vite-plugin-run, which is included by default.
Note that you may add any collector and transformer that you want, and you may annotate any class with
#[TypeScript] for it to be transformed — provided it has a corresponding transformer.