Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Typescript Transformer Laravel Package

spatie/typescript-transformer

Automatically generate TypeScript definitions from your PHP/Laravel code. spatie/typescript-transformer scans classes and types, then outputs .d.ts files so your frontend stays in sync with backend models, DTOs and enums with minimal manual typing.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:
    composer require spatie/typescript-transformer
    
  2. Basic Configuration (Laravel): Add the service provider in config/app.php:
    Spatie\TypeScriptTransformer\TypeScriptTransformerServiceProvider::class,
    
    Publish the config:
    php artisan vendor:publish --provider="Spatie\TypeScriptTransformer\TypeScriptTransformerServiceProvider"
    
  3. First Transformation: Add the #[TypeScript] attribute to a PHP class:
    #[TypeScript]
    class User {
        public int $id;
        public string $name;
    }
    
    Run the Artisan command:
    php artisan typescript:transform
    
    Output will be generated in resources/js/types/ (default) as User.d.ts.

Where to Look First

  • Laravel Integration: Check config/typescript-transformer.php for default settings.
  • Transformers: Focus on AttributedClassTransformer for classes marked with #[TypeScript].
  • Output: Verify output_directory in config (e.g., resources/js/types/).

Implementation Patterns

Core Workflows

  1. Annotated Classes: Use #[TypeScript] on classes to auto-generate TypeScript types. Ideal for models, DTOs, or domain objects.

    #[TypeScript]
    class Post {
        public int $id;
        public string $title;
        public ?Carbon $publishedAt;
    }
    
  2. Enums: Transform PHP enums to TypeScript union types:

    enum Status { case PUBLISHED = 'published'; case DRAFT = 'draft'; }
    

    Output:

    export type Status = 'published' | 'draft';
    
  3. Custom Type Replacements: Replace complex types (e.g., Carbon) in config:

    $config->replaceType(Carbon::class, 'string');
    

Integration Tips

  • Laravel Eloquent Models: Combine with #[TypeScript] and replace Carbon/DateTime to strings:

    $config->replaceType(Carbon::class, 'string');
    $config->transformer(new LaravelAttributedClassTransformer());
    
  • Generics: Use #[TypeScript] on generic classes:

    #[TypeScript]
    class Collection<T> {
        public array $items;
    }
    
  • Artisan Command: Extend the default command for custom logic:

    $config->transformer(new CustomTransformer());
    
  • CI/CD: Add to deployment pipeline to auto-generate types on git push:

    # .github/workflows/deploy.yml
    - run: php artisan typescript:transform
    

Gotchas and Tips

Pitfalls

  1. Circular Dependencies: Avoid circular references between transformed classes (e.g., ClassA references ClassB, which references ClassA). Fix: Use #[TypeScript(ignore: true)] or refactor.

  2. Unresolved Types: Properties without type hints (e.g., public $name) default to any. Explicitly type them:

    public string $name; // Correct
    public $name;       // Avoid (becomes `any`)
    
  3. Namespace Collisions: GlobalNamespaceWriter may cause conflicts if multiple packages generate types with the same namespace. Fix: Use ModuleWriter for isolated output per directory.

  4. Laravel-Specific Quirks:

    • Carbon: Replace with string or custom types to avoid runtime issues.
    • Collections: Use #[TypeScript] on custom collections, not Laravel’s base Collection.

Debugging

  • Verbose Output: Enable debug mode in config:

    'debug' => true,
    

    Run with:

    php artisan typescript:transform --verbose
    
  • Dry Runs: Use RunnerMode::DryRun to preview changes without writing files:

    $runner->run(mode: RunnerMode::DryRun);
    
  • Transformer Order: Transformers execute in registration order. Place AttributedClassTransformer first if using #[TypeScript].

Extension Points

  1. Custom Transformers: Implement Transformer interface for bespoke logic:

    class CustomTransformer implements Transformer {
        public function transform(ReflectionClass $reflectionClass, TransformationContext $context) {
            if ($reflectionClass->isSubclassOf(MyCustomClass::class)) {
                return new Transformed(new TypeScriptObject([...]));
            }
            return new Untransformable();
        }
    }
    
  2. Dynamic Replacements: Use closures for context-aware replacements:

    $config->replaceType(MyClass::class, function (TypeScriptReference $reference) {
        return new TypeScriptString($reference->getName() . '_prefix');
    });
    
  3. Post-Processing: Hook into TypeScriptTransformerConfigFactory to modify config dynamically:

    $factory->modifyUsing(function (TypeScriptTransformerConfig $config) {
        $config->outputDirectory(__DIR__ . '/custom-output');
    });
    

Performance

  • Exclude Directories: Skip irrelevant paths (e.g., tests, vendors) in config:

    $config->excludeDirectories([
        app_path('Tests'),
        vendor_path(),
    ]);
    
  • Cache: Enable caching for large projects:

    $config->cacheDirectory(storage_path('framework/cache/typescript'));
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity