Easily Generate TypeScript Types from your Laravel Code

Easily Generate TypeScript Types from your Laravel Code cover image

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.

Written by

Rizwan Aslam

Founder and CEO of CodeBrisk, with years of experience building web applications with Laravel and leading a team of expert developers.

More about Rizwan
Book a free call
Book a call with CodeBrisk