based/laravel-typescript

将 Laravel 模型转换为 TypeScript 接口

v0.0.4 2023-07-06 21:24 UTC

This package is auto-updated.

Last update: 2024-08-26 20:31:25 UTC


README

Latest Version on Packagist GitHub Tests Action Status Total Downloads

该包允许您从您的 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 接口

declare namespace App.Models {
    export interface 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/models.d.ts'),

    // load namespaces from composer's `dev-autoload`
    'autoloadDev' => false,
];

用法

生成 TypeScript 接口。

php artisan typescript:generate

Vue 3 示例用法

import { defineComponent, PropType } from "vue";

export default defineComponent({
    props: {
        product: {
            type: Object as PropType<App.Models.Product>,
            required: true,
        },
    },
}

测试

composer test

鸣谢

许可

MIT 许可证(MIT)。请参阅 许可文件 以获取更多信息。