Build Typescript Interfaces for Laravel Models

Packages

July 27th, 2021

Build Typescript Interfaces for Laravel Models

Laravel Typescript is a package that lets you generate TypeScript interfaces from your Laravel models. The example from the documentation demonstrates how you can take a complex model with database columns and relationships and quickly generate the TypeScript interfaces for them:

class Product extends Model
{
public function category(): BelongsTo
{
return $this->belongsTo(Category::class);
}
 
public function features(): HasMany
{
return $this->hasMany(Feature::class);
}
}

The above model will translate into the following interface:

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;
}
// ...
}

This package can support database columns, model relationships, model accessors, and planned support for casted attributes.

Finally, here's an example of how you might use this package with a Vue 3 component:

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

You can learn more about this package, get full installation instructions, and view the source code on GitHub.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.