Generating TypeScript types with Tempest
Tempest now has the ability to generate TypeScript interfaces from PHP classes to ease integration with TypeScript-based front-ends.
Tempest 3.1.0 was just released, and with it comes a new generate:typescript-types command. This command will take any value objects, DTOs, or enums written in PHP and generate TypeScript equivalents for them that you can use in your frontend. The only thing you need is annotated PHP code with #[AsType], and Tempest handles the rest.
Let's say you have this class:
namespace App\Web\Blog; use Tempest\Generation\TypeScript\AsType; // … #[AsType] final class BlogPost { public string $slug; public string $title; public ?Author $author; public string $content; public DateTimeImmutable $createdAt; public ?BlogPostTag $tag = null; public ?string $description = null; public bool $published = true; public array $meta = []; public string $uri { get => uri([BlogController::class, 'show'], slug: $this->slug); } public string $metaImageUri { get => uri([MetaImageController::class, 'blog'], slug: $this->slug); } }
Next, you run:
./tempest generate:typescript-types
✓ // Generated 3 type definitions across 1 namespaces.
Which will generate:
/* |---------------------------------------------------------------- | This file contains TypeScript definitions generated by Tempest. |---------------------------------------------------------------- */ export namespace App.Web.Blog { export type Author = 'brent'; export type BlogPostTag = 'release' | 'thoughts' | 'tutorial'; export interface BlogPost { slug: string; title: string; author?: Author; content: string; createdAt: string; tag?: BlogPostTag; description?: string; published: boolean; meta: any[]; uri: string; metaImageUri: string; } }
Of course, Tempest will discover all relevant classes for you, you can optionally configure how TypeScript files are generated, and you can even add your own type resolvers where needed. You can read all about it in the TypeScript docs. A massive thanks to Enzo for building this awesome feature!