alexthekiwi / laravel-typescript
将 Laravel 模型转换为 TypeScript 接口
0.1.2
2023-08-20 02:20 UTC
Requires
- php: ^8.0
- doctrine/dbal: ^3.1
- illuminate/contracts: ^8.37|^9.0|^10.0
- spatie/laravel-package-tools: ^1.11.0
Requires (Dev)
- brianium/paratest: ^6.2
- nunomaduro/collision: ^5.3|^6.1.0
- nunomaduro/larastan: ^0.7.11|^2.0.1
- orchestra/testbench: ^6.15|^7.0.1|^8.0
- phpunit/phpunit: ^9.3
This package is auto-updated.
Last update: 2024-09-20 04:54:11 UTC
README
该包允许您从您的 Laravel 模型生成 TypeScript 类型。
简介
假设您有一个模型,它具有多个属性(数据库列)和多个关系。
class Product extends Model { public function category(): BelongsTo { return $this->belongsTo(Category::class); } public function features(): HasMany { return $this->hasMany(Feature::class); } }
Laravel TypeScript 将生成以下 TypeScript 类型
export type App = { Models: { Product: { id: number; category_id: number; name: string; price: number; created_at: string | null; updated_at: string | null; category?: App.Models.Category | null; features?: Array<App.Models.Feature> | null; } }; ... }
Laravel TypeScript 支持
- 数据库列
- 模型关系
- 模型访问器
- 转换属性
安装
需要 Laravel 8+ 和 PHP 8+。 您可以通过 composer 安装该包
composer require based/laravel-typescript
您可以使用以下命令发布配置文件
php artisan vendor:publish --provider="Based\TypeScript\TypeScriptServiceProvider" --tag="typescript-config"
这是已发布配置文件的内容
return [ 'generators' => [ Model::class => ModelGenerator::class, ], 'output' => resource_path('js/types/models.d.ts'), // load namespaces from composer's `dev-autoload` 'autoloadDev' => false, ];
用法
生成 TypeScript 接口。
php artisan typescript:generate
或快捷方式
php artisan ts:generate
使用 React 的示例用法
import type { App } from '@/types'; interface Props { Product: App['Models']['Product']; }
测试
composer test
致谢
许可协议
MIT 许可协议 (MIT)。请参阅 许可文件 获取更多信息。