Blog Detail

21

Dec
Easily Generate TypeScript Types from your Laravel Code cover image

arrow_back Easily Generate TypeScript Types from your Laravel Code

Laravel Typegen is an awesome library that lets you generate TypeScript types from your Laravel code

Features

  • Generate TypeScript types from Laravel models
  • Support Relationhips
  • Support Enum (from PHP8.1)
  • Generate route.d.ts file for ziggy
  • Provide useful types for Laravel (e.g. pagination, etc.)

Installation

You can install this package via composer:

$ npm install -D @7nohe/laravel-typegen

Usage

Edit package.json

{
    "scripts": {
        "typegen": "laravel-typegen"
    },
}
$ npm run typegen

Enum Support

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"
}

Laravel Enum Support

If you use Laravel Enum, use the option --laravel-enum.

{
    "scripts": {
        "typegen": "laravel-typegen --laravel-enum"
    },
}

Available options

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

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

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 your project

Launch project