trongio / php-ts-types
Generate TypeScript types from PHP classes: a small structural type model, a deterministic emitter with a drift check, a reflection source and Laravel + Inertia integration.
Requires
- php: ^8.3
- phpstan/phpdoc-parser: ^2.0
Requires (Dev)
- illuminate/console: ^11.0|^12.0|^13.0
- illuminate/support: ^11.0|^12.0|^13.0
- phpstan/phpstan: ^2.1
- phpstan/phpstan-strict-rules: ^2.0
- phpunit/phpunit: ^11.0|^12.0
Suggests
- illuminate/console: For the Laravel bridge: php artisan ts-types:generate (^11.0|^12.0|^13.0)
- illuminate/support: For the Laravel bridge's service provider (^11.0|^12.0|^13.0)
- inertiajs/inertia-laravel: For Inertia page props; the page manifest itself needs no Inertia classes
Provides
None
Conflicts
None
Replaces
None
README
Generate TypeScript types from PHP classes, and fail CI when the committed file is stale.
- Core (no Laravel): a small structural type model (
Primitive,Literal,Union,ListType,RecordType,ObjectTypewith optional keys,Reference,Wrappedfor lazy props),TypeDefinitions(name => type, de-duplicated structurally, a different shape under a taken name is an error) andTypeScriptEmitter(one module,export typeonly, sorted, a "generated, do not edit" header, an optional rawappendblock).Writerwrites the file, or checks it and returns a diff head. - Sources: a
TypeSourcedecides which classes become named types and what their wire shape is.PublicPropertiesSourceships: public properties of concrete subclasses of configured bases, or of#[TsType]classes, keys verbatim (orcamel/snake). A second source (for example one that reads atoArray()return type) implements the same interface and passes type strings toTypeGenerator::docType(). - Laravel (optional):
php artisan ts-types:generate [--check] [--output=path], configured byconfig/ts-types.php. Everything undersrc/Laravelneedsilluminate/consoleandilluminate/support, which are only suggested: the core and the sources depend on nothing butphpstan/phpdoc-parser, and a test keeps everyIlluminatereference insidesrc/Laravel. - Inertia:
InertiaPageManifestaddsexport type InertiaPages = { "settings/Notifications": NotificationsProps; ... }. A page's component comes from#[InertiaPage('...')], else from a class constant (COMPONENTby default).Testing\ShapeRulesgives an app architecture test.
Allowed types
| PHP (native or PHPDoc) | TypeScript |
|---|---|
int, float, int refinements |
number |
string, string refinements |
string |
bool, true, false, null |
boolean, true, false, null |
'a', 2 literal types |
"a", 2 |
?T, A|B |
T | null, A | B |
| a backed enum | a named literal union |
| a class a source supports | a named reference |
| a class a leaf mapper maps | the mapped type |
a class leaf-mapped to json |
JsonValue (recursive) |
list<T> |
T[] |
array<string, T> |
Record<string, T> |
array{a: T, 'b'?: U} (sealed) |
{ a: T; b?: U } |
a configured wrapper W<T> (property) |
key?: T |
A wrapper is your own lazy-prop class (an Inertia optional or deferred prop), configured as
'wrappers' => [Optional::class => 'optional']. Kinds: deferred, optional, once, merge (Inertia's lazy
props) and gated (sent eagerly with the page, but left out entirely when it does not apply, e.g. a block the
viewer lacks the permission for). It is read from the property's PHPDoc with its one type
argument (@param Optional<Verdict> $verdict), and the key becomes optional: the server leaves it out. A
nullable wrapper means the same (a null wrapper is a key left out, never a null sent). A wrapper without its
type argument, inside a list, map or shape, or in a union with anything but null is refused.
A json leaf ('leaves' => [MyJson::class => 'json']) is for a value sent exactly as it was stored, such
as a recorded payload: it emits one named recursive type, export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };, never unknown.
Anything else throws, naming Class::$property.key: mixed, object, bare array, T[],
array<int, T>, unsealed or positional shapes, self::CONST types, @phpstan-type aliases, unit enums and
unmapped classes (dates included: map them with a leaf mapper or send strings). It never emits any or
unknown.
Type names are the PHP short names (or #[TsType(name)]) in one flat module. Two classes with the same
short name and an identical shape share one TypeScript type; with different shapes generation fails and
names both FQCNs. Docblock names resolve through the file's use imports, group imports included; a file
with a bracketed namespace X { } block is refused.
Install
composer require --dev trongio/php-ts-types php artisan vendor:publish --tag=ts-types-config
Use it as a dev dependency and commit the generated file: production needs neither.
Configure
// config/ts-types.php return [ 'output' => resource_path('js/types/generated/types.d.ts'), 'discover' => [app_path('Inertia') => 'App\\Inertia'], 'public_properties' => ['bases' => ['App\\Inertia\\PageProps'], 'attribute' => true, 'keys' => 'verbatim'], 'leaves' => ['Carbon\\CarbonInterface' => 'string'], 'inertia' => ['manifest' => true, 'type' => 'InertiaPages', 'constant' => 'COMPONENT'], 'append' => '', ];
Keep the config to strings and arrays so config:cache works where the package is not installed.
Generate and check
php artisan ts-types:generate # write php artisan ts-types:generate --check # exit 1 and print the diff head when stale (CI)
Without Laravel
$generator = new TypeGenerator([new PublicPropertiesSource([MyBase::class])]); $definitions = $generator->generate($classes); $definitions->define('Extra', new ObjectType([new Property('id', Primitive::number())])); echo (new TypeScriptEmitter)->emit($definitions);
Tests
composer install && vendor/bin/phpunit
MIT licensed.