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

Laravel Typescript Transformer Laravel Package

spatie/laravel-typescript-transformer

Convert PHP classes, enums, and more into TypeScript types automatically. Uses attributes to generate TS from your Laravel code, supports nullable and complex types, generics, and even TypeScript functions—keeping your backend and frontend types in sync.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Strong alignment with Laravel’s type system: The package leverages Laravel’s native PHP types (e.g., #[TypeScript], #[MapName]) to generate TypeScript types, ensuring consistency with existing codebases. This reduces friction for teams already using Laravel’s data mapping (e.g., spatie/laravel-data).
  • Modular design: Built on top of spatie/typescript-transformer, which provides a flexible core for extending transformations (e.g., custom writers, formatters like Prettier). This allows TPMs to tailor the output to project-specific needs (e.g., custom naming conventions, nested types).
  • Controller/route integration: Generates typed route helpers and controller action signatures, bridging Laravel’s backend logic with frontend frameworks (e.g., Inertia.js, Vue/React). This is critical for full-stack TypeScript projects.
  • Watch mode: Real-time regeneration of TypeScript types during development reduces manual maintenance overhead.

Integration Feasibility

  • Laravel 10+ requirement: Mandates PHP 8.2+, which may necessitate dependency updates for legacy projects. However, this aligns with Laravel’s long-term support (LTS) roadmap.
  • Dependency on spatie/laravel-data: For advanced features (e.g., MapName attributes), but the package gracefully degrades if not installed (e.g., falls back to default naming).
  • Service provider configuration: Replaces config files with a fluent API, simplifying customization (e.g., httpMethodsPriority, output paths). This is a net positive for maintainability.
  • Artisan commands: Provides typescript:watch, typescript:transform, and typescript:install for seamless CLI integration.

Technical Risk

  • Breaking changes in v3.x: Major rewrite introduces risks for migrations (e.g., config → service provider shift). Mitigation: Thorough testing and phased adoption.
  • Complexity in custom transformations: Advanced use cases (e.g., generics, nested types) may require deep understanding of the transformer’s internals. Documentation and examples help, but debugging edge cases could be challenging.
  • Performance overhead: Watch mode and real-time generation add runtime checks. Benchmarking recommended for large codebases.
  • Frontend framework compatibility: Generated types must align with frontend expectations (e.g., Inertia.js route helpers). Testing with target frameworks is critical.

Key Questions

  1. Frontend ecosystem: Which frontend frameworks/libraries (e.g., Inertia, Livewire, vanilla JS) will consume these types? This dictates priority features (e.g., route helper precision).
  2. Type safety trade-offs: Should the package prioritize strict type fidelity (e.g., preserving Laravel’s null vs. TypeScript’s undefined) or pragmatic compatibility?
  3. CI/CD integration: How will generated types be versioned and deployed? (e.g., Git-ignored node_modules/@types vs. committed .d.ts files).
  4. Custom type mappings: Are there domain-specific PHP types (e.g., custom enums, DTOs) that need special handling?
  5. Legacy support: If migrating from v2.x, what’s the effort to update config/service provider bindings?

Integration Approach

Stack Fit

  • Laravel-centric: Optimized for Laravel’s ecosystem (e.g., controllers, routes, spatie/laravel-data). Minimal overhead for existing Laravel projects.
  • TypeScript-first: Outputs .d.ts files compatible with modern tooling (e.g., TypeScript 5+, Vite, Webpack). Supports Prettier for formatting.
  • Full-stack alignment: Generates types for:
    • Models/DTOs: #[TypeScript]-annotated classes → TypeScript interfaces.
    • Controllers: Action signatures, request/response types.
    • Routes: Typed route() helper with autocompletion.
    • Enums: Native TypeScript enums or union types.
  • Extensible: Plugins for custom transformations (e.g., GraphQL types, API clients).

Migration Path

  1. Assessment:
    • Audit existing PHP types (e.g., #[TypeScript], #[MapName]) and identify gaps.
    • Review frontend type expectations (e.g., Inertia route names vs. Laravel route keys).
  2. Setup:
    • Install package: composer require spatie/laravel-typescript-transformer.
    • Publish config/service provider: php artisan vendor:publish --provider="Spatie\LaravelTypeScriptTransformer\TypeScriptTransformerServiceProvider".
    • Configure in AppServiceProvider:
      TypeScriptTransformer::configure(function (LaravelControllerTransformedProvider $provider) {
          $provider->httpMethodsPriority(['get', 'post', 'put']);
      });
      
  3. Incremental Adoption:
    • Start with critical models/DTOs annotated with #[TypeScript].
    • Enable controller/route generation for high-traffic endpoints.
    • Test watch mode in development (php artisan typescript:watch).
  4. Frontend Sync:
    • Copy generated .d.ts files to frontend project (e.g., resources/js/types).
    • Configure TypeScript to include them in tsconfig.json:
      {
        "compilerOptions": {
          "typeRoots": ["./node_modules/@types", "./resources/js/types"]
        }
      }
      

Compatibility

  • Laravel: Tested on 10+ (LTS). Backward compatibility for 11/12/13 via minor versions.
  • PHP: Requires 8.2+. Use php-version in CI to enforce.
  • TypeScript: Outputs ES6+ syntax. Test with target TypeScript version (e.g., 5.0+).
  • Frontend Frameworks:
    • Inertia.js: Prioritize route helper types (e.g., route('post.create')).
    • Livewire: Focus on component props/emits.
    • Vanilla JS: Ensure generated types work with fetch/axios calls.

Sequencing

  1. Phase 1: Models/DTOs → TypeScript interfaces (low risk, high ROI).
  2. Phase 2: Controllers → Action types (validate with frontend integration).
  3. Phase 3: Routes → Typed helpers (critical for SPAs).
  4. Phase 4: Enums/Custom types (edge cases).
  5. Phase 5: Watch mode + CI/CD automation (dev experience).

Operational Impact

Maintenance

  • Generated Code: .d.ts files are auto-generated; avoid manual edits. Use typescript:transform to regenerate.
  • Dependency Updates: Monitor spatie/typescript-transformer for breaking changes (e.g., v3.x → v4.x). Test upgrades in staging.
  • Custom Transformers: Document any project-specific extensions (e.g., custom writers) in a README.md or wiki.
  • CI Pipeline:
    • Add step to regenerate types on php artisan typescript:transform.
    • Lint generated TypeScript (e.g., tsc --noEmit).
    • Example GitHub Actions:
      - name: Generate TypeScript types
        run: php artisan typescript:transform
      - name: TypeScript lint
        run: tsc --noEmit
      

Support

  • Debugging:
    • Use --verbose flag for Artisan commands to diagnose issues.
    • Check logs for transformer errors (e.g., unsupported PHP types).
    • Frontend errors may stem from mismatched route names (e.g., Laravel home vs. frontend dashboard).
  • Common Issues:
    • Route names: Ensure frontend uses route() helper consistently.
    • Circular dependencies: Exclude problematic classes from transformation.
    • Performance: Disable watch mode in production; use typescript:transform on deploy.
  • Documentation:
    • Maintain a TYPESCRIPT_TRANSFORMER.md with:
      • Annotated examples (e.g., #[TypeScript], #[MapName]).
      • Frontend integration guide.
      • Troubleshooting checklist.

Scaling

  • Large Codebases:
    • Exclusion: Use ignore() in service provider to skip non-critical classes.
    • Parallelization: Transformers are stateless; consider parallelizing generation for CI.
    • Incremental Updates: Use --only-changed flag (if supported) to regenerate only modified files.
  • Team Onboarding:
    • Developer Docs: Highlight:
      • Where to place #[TypeScript] annotations.
      • How to extend types (e.g., custom transformers).
    • Pair Programming: Demo watch mode and real-time feedback.
  • Performance:
    • Watch Mode: Exclude vendor/ and node_modules/ from watched paths.
    • Production: Disable watch mode; regenerate types on deploy (e.g., via deploy.php hook).

Failure Modes

Failure Scenario Impact Mitigation
Transformer crashes on unsupported type Broken CI/CD pipeline
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony