Laravel TypeScript Transformer

repository·main·Indexed 18 days ago

https://github.com/spatie/laravel-typescript-transformer

A package that automates the conversion of PHP classes, enums, and structures into TypeScript types to ensure type safety between Laravel backends and TypeScript frontends. It features the #[TypeScript] attribute for class transformation, support for PHP enums as string union types, and integration with spatie/laravel-data via the DataClassPropertyProcessor. Includes Artisan commands for installation (typescript:install), route dumping (typescript:dump-routes), and type transformation (typescript:transform).

Tokens
1.5K
Snippets
6
Records
7
Agent score
64%

What's inside spatie/laravel-typescript-transformer

  1. Transform PHP classes and enums to TypeScript

    main

    The laravel-typescript-transformer package allows you to automatically generate TypeScript types from your PHP code. By using the #[TypeScript] attribute on PHP classes, you can convert class properties into TypeScript types. It also supports converting PHP enums into TypeScript string union types.

    Class Transformation

    When a class is marked with #[TypeScript], its public properties are mapped to a TypeScript type definition. PHP types like int, string, and nullable types ?string are converted to their TypeScript equivalents (number, string, and string | null).

    Enum Transformation

    PHP enums are converted into TypeScript string union types, representing the backed values of the enum cases.

    #[TypeScript]
    class User
    {
        public int $id;
        public string $name;
        public ?string $address;
    }

    // Becomes:

    export type User = {
        id: number;
        name: string;
        address: string | null;
    }
    enum Languages: string
    {
        case TYPESCRIPT = 'typescript';
        case PHP = 'php';
    }

    // Becomes:

    export type Languages = 'typescript' | 'php';
  2. Install the TypeScript transformer via Artisan

    main

    Run the typescript:install Artisan command to set up the TypeScript transformer in your Laravel application. This command performs two main actions:

    1. Publishes the Service Provider: It uses vendor:publish with the --tag=typescript-transformer-provider tag to publish the TypeScriptTransformerServiceProvider.
    2. Registers the Service Provider: It attempts to automatically register App\Providers\TypeScriptTransformerServiceProvider::class in your bootstrap/providers.php file.

    If the command fails to register the provider automatically, you must manually add App\Providers\TypeScriptTransformerServiceProvider::class to your bootstrap/providers.php file.

    php artisan typescript:install
  3. Configure DataClassPropertyProcessor for Laravel Data classes

    main

    The DataClassPropertyProcessor is used to transform properties of classes using spatie/laravel-data into TypeScript. It handles property renaming via mappers, hiding properties, and managing lazy/optional types.

    Key Behaviors

    • Property Hiding: Properties marked with either Spatie\TypeScriptTransformer\Attributes\Hidden or Spatie\LaravelData\Attributes\Hidden will be excluded from the generated TypeScript.
    • Name Mapping: It respects MapName and MapOutputName attributes from laravel-data. It checks for these attributes on the property itself first, then on the declaring class, and finally falls back to the data.name_mapping_strategy.output configuration value.
    • Lazy and Optional Types: Types that are Spatie\LaravelData\Optional or belong to the internal lazyTypes list (such as Spatie\LaravelData\Lazy or InertiaLazy) are treated as optional in TypeScript. The specific type is removed from the union, and the property is marked as isOptional = true.
    • Nullable as Optional: If configured, null types in a union will be converted to optional properties in TypeScript.

    Constructor Options

    When instantiating the processor, you can provide:

    • customLazyTypes: An array of class strings to be treated as lazy/optional types.
    • nullableAsOptional: A boolean determining if null should be converted to an optional property.
  4. Reference: typescript:dump-routes arguments and options

    main

    The typescript:dump-routes command accepts the following arguments and options:

    • {filters}: A base64 encoded, serialized string representing the filters to apply to the route collection. To pass no filters, use the literal string null.
    • --include-route-closures: A flag that, when present, instructs the command to include route closures in the transformation process.
    Arguments:
      filters                   Base64 encoded, serialized filters (or 'null')
    
    Options:
      --include-route-closures   Include route closures in the output
  5. Reference the `typescript:transform` CLI flags

    main

    The typescript:transform command supports the following options:

    OptionDescription
    --watchWatch for changes and re-transform automatically
    --worker(internal) Run the worker process

    Note on usage: The --worker flag is intended for internal use. If you are attempting to use --worker, it should be used in conjunction with --watch.

    --watch : Watch for changes and re-transform
    --worker : (internal) Run the worker process
  6. Run the TypeScript transformation CLI

    main

    Use the typescript:transform command to trigger the transformation of PHP classes into TypeScript definitions.

    By default, it runs in Direct mode, performing a single transformation pass. You can enable watch mode to monitor file changes and re-transform automatically, or use the worker mode for internal process management.

    If the command fails with a configuration error, ensure you have run php artisan typescript:install to set up the required configuration.

    php artisan typescript:transform
  7. Dump Laravel routes via typescript:dump-routes

    main

    The typescript:dump-routes command transforms Laravel route definitions into a format that the TypeScript Transformer can use. This is typically used as an internal step to bridge Laravel's routing system with TypeScript type generation.

    Note: This command is marked as $hidden = true in the source, meaning it is intended for programmatic use or internal pipeline execution rather than direct manual use by developers in a standard terminal workflow.

    php artisan typescript:dump-routes {filters} {--include-route-closures}