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.

Laravel Forge logo

Laravel Forge

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

Laravel Forge
Tinkerwell logo

Tinkerwell

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

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
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
Bacancy logo

Bacancy

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

Bacancy
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
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
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
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
The Inertia.js v2 Beta is Here image

The Inertia.js v2 Beta is Here

Read article
Mastering Laravel, No Compromises, and SourceDive with Joel Clermont image

Mastering Laravel, No Compromises, and SourceDive with Joel Clermont

Read article
Now you can install PHP and the Laravel installer with a single command image

Now you can install PHP and the Laravel installer with a single command

Read article
WireSpy is a Sleek New Debug Bar for Laravel Livewire image

WireSpy is a Sleek New Debug Bar for Laravel Livewire

Read article
The Laracon AU schedule is now live image

The Laracon AU schedule is now live

Read article
Supercharge PhpStorm with Laravel Idea image

Supercharge PhpStorm with Laravel Idea

Read article