I'm currently developing a monorepo app using Laravel with Blade and Vue components. I'm curious about the best practices for sharing types between PHP and TypeScript. Should I create them separately, or is there a better approach, like generating types? I'm looking for some insights or methods that have worked for you!
6 Answers
You might want to check out this GitHub repo: [laravel-typescript-transformer](https://github.com/spatie/laravel-typescript-transformer). It allows one-way generation from PHP to TypeScript, if you're open to that approach!
I've noticed a trend towards using JSON Schema for defining types as well. It seems to be gaining popularity for interoperable schemas across languages.
I suggest starting with an API-first approach. Use OpenAPI specs to generate the interfaces for both the client (TypeScript) and server (PHP). This way, you'll ensure consistency across your codebase. Check out the OpenAPI Generator for more info!
I completely agree! Defining shared types separately and then consuming them as needed seems like a great method. I personally like using protobuf for this, but OpenAPI/Swagger works just as well for type definitions.
Hey, just define the types separately. It's straightforward and helps to maintain clean code. Just keep the backend and frontend portions aligned as much as possible to avoid duplication.
Thanks for the input! That makes sense, I just want to minimize duplication while keeping types consistent.
Am I the only one who just types out my TypeScript types manually? 🤔
We create OpenAPI schemas to generate both PHP and TypeScript code for our API endpoints. This method also allows runtime validation, which can be super handy.
Thanks for sharing! It looks useful, but might be a bit overkill for my current needs, especially with all the manual setup involved.