Skip to content

TypeScript

Overview

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 integrates well with laravel-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 objects

laravel-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:

bash
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:

bash
composer require spatie/laravel-typescript-transformer
php artisan vendor:publish --tag=typescript-transformer-config

Open config/typescript-transformer.php and update the following properties:

php
'collectors' => [
    Spatie\TypeScriptTransformer\Collectors\DefaultCollector::class,
    Spatie\TypeScriptTransformer\Collectors\EnumCollector::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,
],

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.

Note that Hybridly automatically runs php artisan typescript:generate through vite-plugin-run, which is included by default.

Transform anything

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.