codemystify/laravel-types-generator
Composer 安装命令:
composer require codemystify/laravel-types-generator
包简介
Simplified TypeScript types generator for Laravel applications with developer-defined structure system
关键字:
README 文档
README
I got tired of manually writing TypeScript types for my Laravel APIs, so I built this. It's simple: you tell it exactly what your data looks like, and it generates clean TypeScript interfaces. No magic, no guessing, just straight-forward type generation.
What This Actually Does
You add an attribute to your Laravel classes (like API resources), define the structure, run a command, and get TypeScript files. That's it.
Installation
composer require codemystify/laravel-types-generator
If you want to customize the config:
php artisan vendor:publish --tag=types-generator-config
Quick Example
Here's how I use it in my Laravel API resources:
use Codemystify\TypesGenerator\Attributes\GenerateTypes; class UserResource extends JsonResource { #[GenerateTypes( name: 'User', structure: [ 'id' => 'number', 'name' => 'string', 'email' => 'string', 'avatar' => ['type' => 'string', 'optional' => true], 'created_at' => 'string', ] )] public function toArray($request): array { return [ 'id' => $this->id, 'name' => $this->name, 'email' => $this->email, 'avatar' => $this->avatar, 'created_at' => $this->created_at->toISOString(), ]; } }
Run the command:
php artisan types:generate
Get this TypeScript file:
// user.ts export interface User { id: number; name: string; email: string; avatar?: string; created_at: string; }
How to Define Types
Basic Types
[
'title' => 'string',
'count' => 'number',
'active' => 'boolean',
'data' => 'any', // Use sparingly
]
Optional Fields
For fields that might not be present:
[
'bio' => ['type' => 'string', 'optional' => true], // bio?: string
]
Nullable Fields
For fields that can be null:
[
'deleted_at' => ['type' => 'string', 'nullable' => true], // deleted_at: string | null
]
Arrays
[
'tags' => 'string[]', // Array of strings
'users' => 'User[]', // Array of User interfaces
]
Union Types
[
'status' => 'string|null', // status: string | null
]
Real Example: Blog Post API
Here's how I handle a typical blog post resource:
class PostResource extends JsonResource { #[GenerateTypes( name: 'Post', structure: [ 'id' => 'number', 'title' => 'string', 'slug' => 'string', 'content' => 'string', 'excerpt' => ['type' => 'string', 'nullable' => true], 'published' => 'boolean', 'author' => 'Author', 'tags' => 'string[]', 'created_at' => 'string', 'updated_at' => 'string', ], types: [ 'Author' => [ 'id' => 'number', 'name' => 'string', 'email' => 'string', 'avatar' => ['type' => 'string', 'optional' => true], ] ] )] public function toArray($request): array { return [ 'id' => $this->id, 'title' => $this->title, 'slug' => $this->slug, 'content' => $this->content, 'excerpt' => $this->excerpt, 'published' => $this->published, 'author' => [ 'id' => $this->user->id, 'name' => $this->user->name, 'email' => $this->user->email, 'avatar' => $this->user->avatar, ], 'tags' => $this->tags->pluck('name')->toArray(), 'created_at' => $this->created_at->toISOString(), 'updated_at' => $this->updated_at->toISOString(), ]; } }
This generates two clean interfaces:
// post.ts import type { Author } from './author'; export interface Post { id: number; title: string; slug: string; content: string; excerpt: string | null; published: boolean; author: Author; tags: string[]; created_at: string; updated_at: string; } export interface Author { id: number; name: string; email: string; avatar?: string; }
Commands
Generate Types
php artisan types:generate
Preview Without Writing Files
php artisan types:generate --dry-run
Generate Specific Group
php artisan types:generate --group=api
Using Groups
I organize my types with groups:
#[GenerateTypes(
name: 'AdminUser',
structure: [...],
group: 'admin'
)]
#[GenerateTypes(
name: 'PublicPost',
structure: [...],
group: 'public'
)]
Then generate specific groups:
php artisan types:generate --group=admin
File Organization
All generated files go to resources/js/types/generated/ by default:
resources/js/types/generated/
├── index.ts # Exports everything
├── user.ts
├── post.ts
├── admin-user.ts
└── ...
The index.ts file automatically exports everything:
export * from './user'; export * from './post'; export * from './admin-user';
So in your React/Vue components:
import { User, Post } from '@/types/generated';
Configuration
The defaults work fine, but you can customize:
// config/types-generator.php return [ 'sources' => [ 'app/Http/Resources', 'app/Http/Controllers', 'app/Models', ], 'output' => [ 'base_path' => 'resources/js/types/generated', ], 'files' => [ 'extension' => 'ts', 'naming_pattern' => 'kebab-case', 'add_header_comment' => true, ], ];
Practical Tips
1. Start Simple
Don't try to define everything at once. Start with basic types and add complexity as needed.
2. Mirror Your API Exactly
The structure should match exactly what your API returns. Don't overthink it.
3. Use Optional vs Nullable Correctly
optional: true- field might not exist in the responsenullable: true- field exists but can be null
4. Handle Pagination
#[GenerateTypes(
name: 'PaginatedPosts',
structure: [
'data' => 'Post[]',
'meta' => 'PaginationMeta',
],
types: [
'PaginationMeta' => [
'current_page' => 'number',
'last_page' => 'number',
'per_page' => 'number',
'total' => 'number',
]
]
)]
5. Keep It DRY with Shared Types
Define common types once and reuse them:
// In a base resource or dedicated class 'address' => 'Address', types: [ 'Address' => [ 'street' => 'string', 'city' => 'string', 'country' => 'string', 'postal_code' => 'string', ] ]
Why I Built This
I tried other solutions but they were either:
- Too magic (trying to guess types from code)
- Too complicated (requiring tons of configuration)
- Too unreliable (breaking when Laravel code changed)
This approach is explicit and predictable. You define exactly what you want, and you get exactly that. No surprises.
Troubleshooting
Types not generating?
- Make sure you're using the attribute in classes that the scanner can find
- Check that your
sourcesconfig includes the right directories - Run with
--dry-runto see what would be generated
Import errors in TypeScript?
- The generator creates proper import statements automatically
- Make sure you're importing from the right path
- Check that the
index.tsfile was generated
Want to disable the package in production?
The attributes have no runtime impact, but if you want to remove them:
php artisan types:cleanup --remove-attributes
That's it! Simple, predictable TypeScript type generation for Laravel. No magic, just the types you define.
codemystify/laravel-types-generator 适用场景与选型建议
codemystify/laravel-types-generator 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 253 次下载、GitHub Stars 达 3, 最近一次更新时间为 2025 年 05 月 26 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「generator」 「php」 「javascript」 「api」 「development」 「laravel」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 codemystify/laravel-types-generator 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 codemystify/laravel-types-generator 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 codemystify/laravel-types-generator 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Memio's PrettyPrinter, used to generate PHP code from given Model
Generates a Blade directive exporting all of your named Laravel routes. Also provides a nice route() helper function in JavaScript.
Caching and compression for Twig assets (JavaScript and CSS).
A pretty nice way to expose your translation messages to your JavaScript.
PHP client for the Google Closure Compiler API in one file.
Yii2 integration for AirBnB Polyglot.js
统计信息
- 总下载量: 253
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 3
- 点击次数: 12
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-05-26