If you write modern PHP, with type declarations on everything and PHPStan or Psalm in your pipeline, you already think the way TypeScript wants you to. This is a quick guide for experienced PHP developers, covering what carries over, what's genuinely different and how to use TypeScript alongside PHP rather than instead of it.
If you're new to TypeScript altogether, start with my introduction to TypeScript, which covers what it is and why it's worth learning.
The one big difference: types disappear
In PHP, type declarations are enforced while your code runs. Pass a string to a function that expects an int in strict mode and you get a TypeError.
TypeScript works the other way round. Types are checked before your code runs and then removed completely, leaving plain JavaScript. Nothing checks them at runtime.
The closest PHP comparison is PHPStan or Psalm on its strictest level, built into the language. That's a useful way to think about it:
tsc, the TypeScript compiler, is your static analyser.- Your editor runs it constantly, so you see problems as you type.
- Anything that arrives while the code is running, such as API responses, form input or saved data, hasn't been checked by anything. You still need to validate it, in the same way as you'd validate a request in PHP.
A quick translation table
| PHP | TypeScript |
|---|---|
int, float |
number (one type for both) |
string, bool |
string, boolean |
?string |
string | null |
string|int |
string | number |
mixed |
unknown (avoid any, which switches checking off) |
void, never |
void, never |
array as a list |
string[], Post[] |
array as a dictionary |
Record<string, number> or a Map |
| PHPStan array shapes | object types and interfaces |
Backed enum |
a union of string values |
Generics in docblocks (@template) |
real generics |
readonly |
readonly |
namespace and use |
ES modules: import and export |
| Traits | no direct equivalent |
| Composer | npm |
| PHPStan or Psalm | tsc |
| PHPUnit or Pest | Vitest, Jest or Node's built-in test runner |
| PHP-CS-Fixer or PHP_CodeSniffer | ESLint and Prettier |
A few of these are worth a closer look.
Interfaces are matched by shape
In PHP, a class only satisfies an interface if it says implements. TypeScript is structurally typed: anything with the right properties fits, whether or not it mentions the interface. That means an interface is really a description of a shape:
interface HasName {
name: string;
}
function greet(thing: HasName): string {
return `Hello ${thing.name}`;
}
const user = { name: "Keith", email: "keith@example.com" };
greet(user); // fine: user has a name, and the extra email doesn't matter
TypeScript does have one safety net. If you write an object out in full, right where it's used, extra properties are flagged as a probable typo:
error TS2353: Object literal may only specify known properties, and 'email' does not exist in type 'HasName'.
Plain objects instead of classes
TypeScript has classes, with private, readonly, abstract and the rest, and a PHP value object translates quite directly:
final class Invoice
{
public function __construct(
public readonly string $number,
public readonly int $totalPence,
public readonly ?string $paidAt = null,
) {}
public function isPaid(): bool
{
return $this->paidAt !== null;
}
}
class Invoice {
readonly number: string;
readonly totalPence: number;
readonly paidAt: string | null;
constructor(number: string, totalPence: number, paidAt: string | null = null) {
this.number = number;
this.totalPence = totalPence;
this.paidAt = paidAt;
}
isPaid(): boolean {
return this.paidAt !== null;
}
}
TypeScript has a shorthand like PHP's constructor promotion, but it's one of the few features that isn't just a type and has to be converted into extra JavaScript. Tools that simply strip types, including Node.js, don't support it, so many projects avoid it.
In practice, though, TypeScript code uses far fewer classes than PHP. Data that comes from JSON is a plain object, not an instance of a class, so the usual pattern is an interface describing the data plus plain functions that work with it:
interface Invoice {
readonly number: string;
readonly totalPence: number;
readonly paidAt: string | null;
}
function isPaid(invoice: Invoice): boolean {
return invoice.paidAt !== null;
}
If you've used PHPStan array shapes such as array{number: string, totalPence: int}, this is the same idea, with the compiler and your editor fully understanding it.
Enums are usually unions
PHP 8.1's backed enums have a TypeScript equivalent, but most TypeScript developers use a union of string values instead:
type PostStatus = "draft" | "published";
It's lighter, it's exactly what arrives in JSON from your PHP API, and TypeScript still checks every value and every switch. TypeScript's own enum keyword, like the constructor shorthand above, needs extra JavaScript generating, so it doesn't work where types are simply stripped.
Generics are real
If you've written @template T in a docblock to keep PHPStan happy, you'll like this. Generics are part of the language:
function first<T>(items: T[]): T | undefined {
return items[0];
}
Call first with an array of strings and TypeScript knows you get back a string, or undefined if the array is empty, and it won't let you forget that second case.
Numbers, null and undefined
- There's no separate integer type.
numbercovers both, and it's a floating-point number, so the classic0.1 + 0.2rounding problem applies. Keep money in whole pence or cents, as you probably already do in PHP. - There are two kinds of nothing.
nullworks much as it does in PHP, andundefinedmeans a value was never set, such as a missing property or an optional parameter that wasn't passed. TypeScript's strict mode makes you handle both, which is the source of most early compiler errors and most of the bugs it saves you from. - Always use
===. You already know why.
Async is the biggest mindset shift
PHP code runs from top to bottom. When you make an HTTP request or query a database, PHP waits for the answer.
JavaScript doesn't wait. Anything that takes time returns a Promise, and you use await inside an async function to wait for the result. TypeScript helps here, because a Promise of something isn't the same type as the thing itself:
interface Post {
id: number;
title: string;
}
async function fetchPosts(): Promise<Post[]> {
const response = await fetch("/api/posts");
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
return response.json();
}
const posts: Post[] = fetchPosts(); // forgot the await
error TS2740: Type 'Promise<Post[]>' is missing the following properties from type 'Post[]': length, pop, push, concat, and 29 more.
response.json() is typed as any, so TypeScript takes your word that the API returns Post[]. That's the "types disappear" rule again: if you don't control the API, check the data, either with your own checks or with a validation library such as Zod.
If you write TypeScript for Node.js on the server, there's a second shift. PHP starts fresh for every request and throws everything away afterwards. A Node.js server is one long-running process, so anything you store in a module-level variable is shared between every request and every visitor until the server restarts. That's useful for caching, and a serious bug if it's someone's basket.
Using TypeScript alongside PHP
For most PHP developers the question isn't whether to switch, but how to use TypeScript for the JavaScript side of a PHP project.
- Laravel. The official React and Vue starter kits use TypeScript, with Inertia connecting them to your Laravel routes and controllers. They're a good way to see a well-organised Laravel and TypeScript project.
- WordPress.
@wordpress/scriptscan compile TypeScript, so block development can use it, and the Interactivity API has a guide to using it with TypeScript. Type coverage across the WordPress packages is still patchy, so expect a few gaps. - Sharing types between PHP and TypeScript. The best way to keep both sides in step is to generate the TypeScript types from the PHP side, so a change to your PHP can't silently break the front end. Spatie's TypeScript Transformer converts PHP classes and enums into TypeScript types, and there's a Laravel version. If your API has an OpenAPI description, tools such as openapi-typescript can generate the types from that instead.
Where to start
- Install TypeScript in a project with
npm install --save-dev typescriptand create atsconfig.json. Strict mode is on by default, and you should leave it on. - Use an editor with good TypeScript support. VS Code has it built in, and PhpStorm and WebStorm handle it well.
- Convert one JavaScript file at a time, starting with the one that breaks most often.
- Run
tscin CI, exactly as you run PHPStan.
TypeScript 7 was released this week, with a rewritten compiler that's often around 10 times faster, so there's never been a better time to add it to your pipeline. It checks code exactly as before, so everything here applies whichever version you use.
If you'd like a hand bringing TypeScript into a Laravel, WordPress or other PHP project, take a look at my website development services or get in touch.