juanparati/model2ts

一个工匠命令,可以将 Eloquent 模型生成 TypeScript 接口。

1.0 2020-10-29 16:04 UTC

This package is auto-updated.

Last update: 2024-08-29 05:54:04 UTC


README

这是什么?

一个工匠命令,可以将 Eloquent 模型翻译成 TypeScript 接口。

Model2Ts 使用反射技术检查模型结构以及相关的表结构,以正确推断类型。

安装

    composer require juanparati/model2ts --dev

用法

为特定模型生成 TypeScript 接口

    artisan model2ts:generate "App\Models\User" user.ts

以下参数可以改变命令的行为

    --ignore-hidden     : Discard attributes registered in $hidden property
    --ignore-casts      : Do not use $casts property in order to infer the attributes types
    --ignore-appends    : Do not include virtual accessor located in $appends property
    --ignore-accessors  : Do not infer types from model accessors.

访问器类型推断

Model2Ts 可以从原生访问器以及注册在 $appends 属性中的虚拟访问器中推断类型。

为了使其工作,类型推断需要在每个访问器方法中定义返回类型。

示例

    public function getFirstnameAttribute() : string {
        return explode(' ', $this->attributes['name'])[0];
    }

数据结构推断

一些数据库类型难以推断某些属性的类型,因为它们可能用于存储结构化数据。这包括 blob 和 text 字段。在这种情况下,接口文件将包含注释,指出字段可能包含结构化类型,如对象或数组。