Outsource Laravel Development Partner - $3200/Month | Bacancy

Typescript with Laravel

Published on by

Typescript with Laravel image

A growing number of PHP and, more specifically, Laravel developers have started to write more strongly typed code, while full-stack developers tend not to apply the same practices to their front end code. One reason is that TypeScript is considered a "different" way to write front end components.

The main misconception is that TypeScript is too complex for primarily backend developers and only bloats code without providing any extra value.

In reality, TypeScript does not force you to declare types. Here is the important part: TypeScript is a JavaScript superset that enables you to add things on top, but any valid JS is also valid TS.

The real-world impact of this is that you can rename your file from .js to .ts and gradually add types or start using types in new files. Your codebase does not have to reach 100% type coverage ever. You can use TypeScript to the extent you choose.

Why TypeScript

TypeScript provides optional static typing, which lets you structure and validate your code at the compilation stage. It also brings the IDE autocompletion and validation support along with the code navigation feature. In short, TypeScript enhances code readability and improves the debugging process.

Adding TypeScript support to your Laravel project is quite simple and only takes minutes but can boost your front-end experience. Let's review the process with a fresh Laravel Breeze install with Vue 3 on board.

1. Install the dependencies

Let's start with installing the TypeScript compiler and corresponding Webpack loader.

npm install ts-loader typescript --save-dev
# or
yarn add ts-loader typescript -D

2. Set up the TypeScript config

TypeScript compiler needs a configuration file containing required options. It is also desirable for proper IDE autocompletion.

tsconfig.json

{
"compilerOptions": {
"target": "es5",
"module": "es2020",
"moduleResolution": "node",
"baseUrl": "./",
"strict": true, // Enable strict type-checking options
"skipLibCheck": true, // Skip type checking of declaration files
"noImplicitAny": false // Bypass raising errors on `any` type
},
"include": ["resources/js/**/*"] // Frontend paths pattern
}

3. Configure Laravel Mix

Initial Laravel installation comes with a boilerplate JavaScript entry point, which needs to get converted into TypeScript. All you need is to rename .js to .ts.

-resources/js/app.js
+resources/js/app.ts

Then, let Mix know that it should handle the JavaScript code as TypeScript. Laravel Mix comes with built-in TypeScript support.

webpack.mix.js

-mix.js('resources/js/app.js', 'public/js')
+mix.ts('resources/js/app.ts', 'public/js')

You also need to tell the compiler and the IDE that the components' code must be treated as TypeScript. Append the lang="ts" part to the components script part.

<script lang="ts">
import { defineComponent } from "@vue/runtime-core";
 
export default defineComponent({
...
});
</script>

That is it; you are all set! You can keep writing code the way you used to and utilize some TypeScript features and improve your front-end experience.

Example usage

TypeScript lets you type-hint variables and methods with simple types as well as with complex structs. As we primarily focus on interacting with a backend, let's look at the example of interacting with a model.

Let's create a file that will contain all the necessary types' declarations – resources/js/types.d.ts.

Say you have a model User that you interact with from the front-end side. Here is the basic TypeScript representation of a default User model. It describes what properties an object could have and what types the properties should be.

resources/js/types.d.js

declare interface User {
id: number;
name: string;
email: string;
}

Now, you can use this interface when assigning variables or returning a value from methods.

let user = <User>{ id: 1, name: 'Taylor Otwell' }
 
function getUser(): User {
...
}

So, when you access the user variable, your IDE will suggest the corresponding object properties. And it also will let you know when the type error appears before you even compile the code.

Writing interfaces for all models and keeping them in sync with your backend code requires extra time. You may want to consider using the laravel-typescript package, which lets you transform your Laravel models into TypeScript declarations and keep them up to date with your migrations.

Boris Lepikhin photo

Founder at Reel. Full stack web developer. Making tricky things with Laravel, Inertia.js and Tailwind CSS.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Docker Support in Laravel VS Code Extension v1.4.2 image

Docker Support in Laravel VS Code Extension v1.4.2

Read article
Laravel Deadlock: Manage Technical Debt with Expiring Code Markers image

Laravel Deadlock: Manage Technical Debt with Expiring Code Markers

Read article
Filament v5 Released With Livewire v4 Support and a New Blueprint Tool image

Filament v5 Released With Livewire v4 Support and a New Blueprint Tool

Read article
Async Request Cancellation Updates in Inertia v2.3.10 image

Async Request Cancellation Updates in Inertia v2.3.10

Read article
FluentVox: AI Text-to-Speech for Laravel with Voice Cloning and GPU Acceleration image

FluentVox: AI Text-to-Speech for Laravel with Voice Cloning and GPU Acceleration

Read article
Laravel Boost v1.8.10 Released With New AI Prompts and Livewire v4 Support image

Laravel Boost v1.8.10 Released With New AI Prompts and Livewire v4 Support

Read article