Skip to content
Advertisement

Export PHP interface to Typescript interface, or vice versa?

I’m experimenting with Typescript, and at my current contract I code backend in PHP.

In a couple of projects I’ve written Typescript interfaces for the sort of AJAX responses my back end code gives so that the frontend developer (sometimes also me, sometimes someone else) knows what to expect and gets type checking and so on.

After writing a few such back end services it seems like the interface and related classes for the responses should exist on the PHP side too. And that makes me think that it’d be nice if I could write them in just one of the two languages and run some build-time tool (I’d invoke it with a gulp task, before the Typescript compiler runs) to export these interfaces to the other language.

Does such a thing exist? Is it possible? Practical?

(I realize PHP is not strongly typed, but if the interfaces were written in PHP there could be some type hinting there such as docstrings which the exporter recognizes and carries over to Typescript.)

Advertisement

Answer

You can use amazing nikic/PHP-Parser to create a tool for converting selected PHP classes (those with @TypeScriptMe string in phpDoc) to TypeScript interfaces quite easily. The following script is really simple one but I think you can expand it and you can generate TypeScript interfaces automatically and possibly track changes through git.

Example

For this input:

JavaScript

you’ll get:

JavaScript

Source codes

index.php:

JavaScript

composer.json

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement