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

Technical Evaluation

Architecture Fit

  • Strong Fit for Laravel/PHP-to-TypeScript Workflows: The package is purpose-built for converting PHP classes (including enums, interfaces, and attributed classes) into TypeScript types, aligning perfectly with Laravel’s backend-frontend type synchronization needs. It bridges the gap between PHP’s runtime typing and TypeScript’s static typing, reducing manual type definition efforts.
  • Modular and Extensible: The package’s architecture is built around transformers (e.g., ClassTransformer, EnumTransformer, AttributedClassTransformer) and writers (e.g., GlobalNamespaceWriter, ModuleWriter), allowing TPMs to customize behavior without monolithic refactoring. This modularity supports incremental adoption (e.g., starting with enums before full class conversion).
  • Laravel-Specific Optimizations: The LaravelAttributedClassTransformer and Laravel-specific CLI integration (php artisan typescript:transform) reduce friction for Laravel teams, making it a low-effort addition to existing workflows.

Integration Feasibility

  • Low-Coupling Design: The package operates on reflection and file I/O, requiring no changes to existing PHP logic. It can be invoked via CLI (e.g., post-deploy or in CI/CD) or integrated into Laravel’s service container for runtime generation.
  • Configuration-Driven: Centralized config (e.g., TypeScriptTransformerConfigFactory) simplifies setup, with options to:
    • Scope transformations to specific directories (transformDirectories()).
    • Replace PHP types with custom TypeScript types (e.g., DateTimestring).
    • Control output structure (global namespace vs. modular files).
  • Dependency Lightweight: Only requires PHP 8.1+ and Composer, with no heavy runtime overhead. TypeScript output is generated at build time or on-demand.

Technical Risk

  • Type Inference Limitations:
    • Risk: Complex PHP types (e.g., dynamic properties, magic methods, or non-standard PHPDoc annotations) may not translate accurately to TypeScript. For example, mixed becomes any, which could weaken type safety.
    • Mitigation: Use @var annotations or custom transformers for edge cases. The package’s replaceType() method allows manual overrides.
  • Build Process Integration:
    • Risk: Generated TypeScript files must be synced with frontend projects. If not version-controlled or watched, manual updates may be needed.
    • Mitigation: Treat generated files as part of the codebase (e.g., commit to Git) or integrate with tools like laravel-mix or vite for hot-reloading.
  • Performance at Scale:
    • Risk: Large codebases with thousands of classes may slow down reflection-based processing.
    • Mitigation: Use transformDirectories() to limit scope and cache reflection results if extending the package.
  • Breaking Changes:
    • Risk: Future PHP/TypeScript syntax changes (e.g., PHP 9’s union types) may require package updates.
    • Mitigation: Monitor the changelog and test upgrades incrementally.

Key Questions for TPM

  1. Scope of Adoption:
    • Should we start with high-value types (e.g., DTOs, enums) or full class conversion? Prioritize based on frontend dependency needs.
  2. Output Management:
    • Will generated TypeScript be version-controlled, or dynamically synced with frontend repos? Impact on CI/CD pipelines.
  3. Customization Needs:
    • Are there PHP types (e.g., custom collections, Eloquent models) that require custom transformers or replacements?
  4. CI/CD Integration:
    • Should transformations run on every deploy, or only during major schema changes? Balance between automation and manual review.
  5. Team Buy-In:
    • How will frontend/backend teams collaborate on type definitions? Define ownership (e.g., backend owns PHP types, frontend validates TypeScript).

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Native CLI Support: The package provides a Laravel-specific Artisan command (typescript:transform), reducing setup time.
    • Service Provider: Can be bootstrapped via TypeScriptTransformerServiceProvider for runtime integration (e.g., generating types on-demand for API responses).
    • Compatibility: Works alongside existing tools like laravel-ide-helper (for PHPStorm) or inertiajs (for frontend-backend type sharing).
  • TypeScript/JavaScript Stack:
    • Outputs .d.ts files (for types-only) or .ts files (for types + executable code), compatible with:
      • Vite/Webpack for bundling.
      • Next.js/React for component props.
      • Deno/Node.js for backend TypeScript.
  • Database/ORM Layer:
    • Can transform Eloquent models (if annotated with #[TypeScript]) to TypeScript interfaces for API responses, reducing boilerplate in controllers.

Migration Path

  1. Pilot Phase (Low Risk):

    • Step 1: Transform enums and simple DTOs to validate the pipeline.
      #[TypeScript]
      class UserRole {
          public const ADMIN = 'admin';
          public const USER = 'user';
      }
      
      Output:
      export type UserRole = 'admin' | 'user';
      
    • Step 2: Integrate the CLI into CI/CD (e.g., run php artisan typescript:transform in GitHub Actions).
    • Step 3: Add generated .d.ts files to the frontend repo (or use a shared monorepo).
  2. Full Adoption (Moderate Risk):

    • Step 4: Annotate core domain classes (e.g., User, Order) with #[TypeScript] and configure transformers.
    • Step 5: Replace manual TypeScript interfaces with generated ones in frontend projects.
    • Step 6: Extend for complex types (e.g., custom collections, nested objects) using replaceType().
  3. Advanced Customization (High Risk/Reward):

    • Step 7: Build custom transformers for unsupported PHP features (e.g., traits, interfaces).
    • Step 8: Integrate with API response wrappers (e.g., Laravel’s JsonResource) to auto-generate TypeScript types for API contracts.

Compatibility

  • PHP Version: Requires PHP 8.1+ (supports attributes, union types). Laravel 9+ is recommended.
  • TypeScript Version: Output is compatible with TypeScript 4.0+. No version conflicts expected.
  • IDE Support: Generated .d.ts files work with VSCode, WebStorm, and PHPStorm for autocompletion.
  • Tooling:
    • Laravel Mix/Vite: Can watch generated files for changes.
    • Docker: Package can run in isolated containers for CI/CD.
    • Monorepos: Works with tools like Turborepo or Nx for shared type definitions.

Sequencing

Phase Task Dependencies Output
Discovery Audit PHP classes/enums for TypeScript conversion potential. None List of candidate classes.
Setup Install package, configure config/typescript-transformer.php. PHP 8.1+, Laravel 9+ Basic config.
Pilot Transform enums/DTOs, test frontend integration. CI/CD pipeline Generated .d.ts files.
Validation Manual review of generated types against frontend needs. Frontend team feedback Refined config/replacements.
Scaling Annotate domain classes, extend transformers for complex types. Custom transformers (if needed) Expanded type coverage.
Automation Integrate into CI/CD, sync with frontend repos. GitHub Actions/GitLab CI Automated type generation.

Operational Impact

Maintenance

  • Configuration Drift:
    • Risk: Changes to PHP classes (e.g., renamed properties) may break TypeScript types.
    • Mitigation:
      • Treat generated files as code (commit to Git).
      • Use CI checks to validate TypeScript compiles after PHP changes.
      • Document the transformation rules for the team.
  • Dependency Updates:
    • Risk: Package updates may introduce breaking changes (e.g., new PHP syntax support).
    • Mitigation:
      • Test updates in a staging environment.
      • Use semantic versioning (^3.0) to avoid major version surprises.
  • Custom Transformer Maintenance:
    • Risk: Bespoke transformers may become outdated if PHP/TypeScript evolves.
    • Mitigation:
      • Isolate custom logic in separate packages.
      • Add tests for custom transformers.

Support

  • Debugging:
    • Tools: The package includes logging (e.g., SymfonyConsoleLogger) and verbose output flags for troubleshooting.
    • Common Issues:
      • Missing Types: Ensure classes are annotated with #[TypeScript] or included in `transform
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