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 in Laravel. Mark PHP code with attributes, handle complex types and generics, and generate TS-friendly definitions (and even functions) to keep frontend types in sync.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Strong alignment with Laravel ecosystem: Designed natively for Laravel, leveraging its service container, Artisan commands, and package architecture. The 3.x rewrite introduces Laravel-specific features (e.g., controller/route type generation) that align with modern Laravel development patterns.
  • TypeScript-first mindset: Solves a critical pain point for full-stack Laravel/TypeScript teams by bridging PHP and TypeScript type systems. Enables type-safe API contracts, reducing runtime errors in frontend-backend communication.
  • Extensible core: Built on spatie/typescript-transformer (v3), which supports complex PHP constructs (generics, enums, attributes) and custom transformers. Allows TPMs to extend or override default behavior (e.g., for custom DTOs or Laravel-specific types like Carbon).

Integration Feasibility

  • Minimal boilerplate: Requires only:
    • composer require spatie/laravel-typescript-transformer
    • Service provider configuration (replaces legacy config files).
    • Optional: Custom transformers for niche use cases.
  • Artisan integration: Provides CLI commands (typescript:transform, typescript:watch) for seamless CI/CD or local development workflows.
  • Watch mode: Automatically regenerates TypeScript on file changes, ideal for developer productivity in monorepos or hybrid stacks.

Technical Risk

Risk Area Assessment Mitigation Strategy
Breaking changes v3.x requires PHP 8.2+ and Laravel 10+. Legacy projects face migration cost. Phase adoption: Start with v2.x for older stacks, migrate incrementally.
Type accuracy Complex PHP constructs (e.g., generics, attributes) may need custom transformers. Test edge cases early; leverage TypeReflectors for custom logic.
Build overhead TypeScript generation adds build steps (e.g., watch mode, CI). Optimize with exclude patterns in config; cache generated files.
Dependency bloat Pulls in spatie/typescript-transformer (~50KB) and optional formatters (e.g., Prettier). Audit dependencies; use composer why spatie/laravel-typescript-transformer to validate.

Key Questions for TPM

  1. Stack compatibility:
    • Are we using Laravel 10+ and PHP 8.2+? If not, can we justify the upgrade?
    • Do we need custom transformers for proprietary PHP types (e.g., legacy DTOs)?
  2. Adoption scope:
    • Should we enforce TypeScript types for all API responses (via middleware/transformers) or opt-in?
    • How will we version TypeScript types alongside API contracts (e.g., v1/user.types.ts)?
  3. CI/CD impact:
    • Should TypeScript generation run in CI (e.g., GitHub Actions) or locally only?
    • How will we handle failed transformations (e.g., break builds or log warnings)?
  4. Long-term maintenance:
    • Who will update transformers if PHP/TypeScript standards evolve (e.g., PHP 9.0 features)?
    • Should we contribute back fixes for Laravel-specific edge cases?

Integration Approach

Stack Fit

  • Primary use case: Laravel + TypeScript (React/Vue/Svelte) full-stack apps where API contracts need type safety.
  • Secondary use cases:
    • Monorepos: Share types between PHP (Laravel) and JS/TS services.
    • Legacy migration: Gradually add TypeScript types to existing PHP codebases.
  • Anti-patterns:
    • Avoid for PHP-only backends or projects without a TypeScript frontend.
    • Not ideal for microservices where API contracts are defined separately (e.g., OpenAPI).

Migration Path

Phase Action Tools/Commands
Assessment Audit PHP classes/enums for TypeScript compatibility. phpstan or manual review.
Setup Install package and configure service provider. composer require spatie/laravel-typescript-transformer + php artisan vendor:publish --provider="Spatie\LaravelTypeScriptTransformer\TypeScriptTransformerServiceProvider"
Pilot Transform a single module (e.g., User model + controller). php artisan typescript:transform (or watch mode).
Enforcement Add [TypeScript] attribute to critical classes. Use #[TypeScript] on models, DTOs, and API responses.
CI Integration Add TypeScript generation to build pipeline. GitHub Actions: php artisan typescript:transform + prettier --write.
Frontend Sync Import generated types into frontend projects. import type { User } from './generated/types';

Compatibility

  • Laravel features supported:
    • Models (Eloquent), DTOs, controllers, routes, enums, collections, and generics.
    • Works with Laravel Breeze/Jetstream for auth types (e.g., User).
  • Limitations:
    • Dynamic properties (e.g., __get()) may not transform cleanly.
    • Closures/callbacks require custom transformers.
    • Laravel-specific types (e.g., HasFactory) need manual mapping (e.g., to string).
  • Dependencies:
    • Requires spatie/typescript-transformer ^3.0 (no conflicts with other Spatie packages).

Sequencing

  1. Start with core models: Transform User, Product, etc., to ensure API contracts are type-safe.
  2. Add controllers: Generate types for request/response pairs (e.g., StoreUserRequestUser).
  3. Routes: Enable typed route helpers (e.g., route('user.show', { user: userId })).
  4. Frontend integration: Update frontend to use generated types (e.g., React hooks, API clients).
  5. CI/CD: Automate generation in PR checks or deployments.

Operational Impact

Maintenance

  • Pros:
    • Reduces frontend-backend drift: TypeScript types are auto-generated from PHP, ensuring consistency.
    • Self-documenting: Types serve as living documentation for API contracts.
    • Low runtime overhead: Generation happens at build time, not runtime.
  • Cons:
    • Transformer maintenance: Custom transformers may need updates if PHP/TypeScript standards change.
    • Build complexity: Adds a dependency on TypeScript tooling (e.g., Prettier, tsc).
  • Best practices:
    • Version types: Use semantic versioning for generated files (e.g., types/v1/).
    • Test transformers: Add PHPUnit/Pest tests for critical classes.
    • Document custom logic: Comment why/where custom transformers are used.

Support

  • Debugging:
    • Use php artisan typescript:transform --verbose for detailed logs.
    • Check storage/framework/views for generated TypeScript (or custom output path).
  • Common issues:
    • Type mismatches: PHP null vs. TypeScript undefined (configure nullToOptional).
    • Circular dependencies: Exclude problematic classes from generation.
    • Frontend errors: Ensure frontend imports types correctly (e.g., paths, aliases).
  • Support channels:
    • GitHub issues for package bugs.
    • Spatie’s docs for Laravel-specific guides.

Scaling

  • Performance:
    • Watch mode: Uses file system events; may impact performance on large codebases (test with npx tsup --watch equivalent).
    • CI: Parallelize generation for multiple modules (e.g., split by User, Order).
  • Large codebases:
    • Exclude patterns: Use exclude in config to skip non-critical classes.
    • Incremental adoption: Start with API-facing classes, then expand.
  • Monorepos:
    • Shared config: Centralize TypeScript transformer settings (e.g., output paths).
    • Cross-language imports: Use projectReferences in tsconfig.json to link PHP-generated types.

Failure Modes

Failure Scenario Impact Mitigation
Transformation errors Build breaks on invalid PHP. Use --ignore-errors in CI; log warnings instead of failing.
Type drift Frontend/backend types diverge. Enforce CI checks (e.g., diff generated types between runs).
Custom transformer bugs Incorrect TypeScript output. Add unit tests for custom transformers.
Watch mode instability High CPU/memory usage. Limit watched
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport