21
DecLaravel Typegen is an awesome library that lets you generate TypeScript types from your Laravel code
You can install this package via composer:
$ npm install -D @7nohe/laravel-typegen
Edit package.json
{
"scripts": {
"typegen": "laravel-typegen"
},
}
$ npm run typegen
We also support php8.1 enums.
<!-- app/Enums/GenderType.php -->
<?php
namespace App\Enums;
enum GenderType: string
{
case Male = 'Male';
case Female = 'Female';
case Other = 'Other';
}
Then,cast model attributes to enums.
<!-- app/Models/User.php -->
<?php
namespace App\Models;
use App\Enums\GenderType;
class User extends Authenticatable
{
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'gender' => GenderType::class,
];
This library will generate the following TypeScript types:
export type User = {
id: number;
name: string;
email: string;
gender: GenderType;
email_verified_at?: string;
created_at?: string;
updated_at?: string;
posts?: Post[];
};
export enum GenderType {
Male = "Male",
Female = "Female",
Other = "Other"
}
If you use Laravel Enum, use the option --laravel-enum.
{
"scripts": {
"typegen": "laravel-typegen --laravel-enum"
},
}
Usage: laravel-typegen [options]
Generate TypeScript types from your Laravel models
Options:
-V, --version output the version number
-o, --output <value> Output directory (default: "resources/ts/types")
--laravel-enum Use Laravel Enum (default: false)
--enum-path <value> Path to enum files (default: "app/Enums")
-z, --ziggy Generate types for ziggy (default: false)
-h, --help display help for command
For more details and source code, Visit Github.
Published at : 21-12-2022
I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.
Launch project