Try Depot: Bring ultra-fast, remote Docker builds directly to your Laravel workflow

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
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech
Tinkerwell logo

Tinkerwell

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

Tinkerwell
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
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
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
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 →
Laravel Pint Now Replaces Fully Qualified Class Names with Imports image

Laravel Pint Now Replaces Fully Qualified Class Names with Imports

Read article
Inertia v3 Upgrade Prompt and JSON Log Support in Laravel Boost v2.3.0 image

Inertia v3 Upgrade Prompt and JSON Log Support in Laravel Boost v2.3.0

Read article
Laracon AU Returns to Brisbane - Call for Speakers Now Open image

Laracon AU Returns to Brisbane - Call for Speakers Now Open

Read article
LaraCopilot: Generate Laravel MVPs From a Single Prompt With AI image

LaraCopilot: Generate Laravel MVPs From a Single Prompt With AI

Read article
Model::withoutRelation() in Laravel 12.54.0 image

Model::withoutRelation() in Laravel 12.54.0

Read article
Tyro Checkpoint: Instant SQLite Snapshots for Laravel Local Development image

Tyro Checkpoint: Instant SQLite Snapshots for Laravel Local Development

Read article