Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Typescript Interfaces from Java Interfaces

I have a Java server application, which uses Jackson to generically serialize DTO's using the reflection API. For example for this DTO interface:

package com.acme.library;
public interface Book { 
  com.acme.library.Author getAuthor();
  String getTitle();
}

From the POJO implementation of this interface, Jackson will generically serialize the following entity:

{
   "author": { "name": "F. Scott Fitzgerald"},
   "title": "The Great Gatsby"
}

This payload will be recieved using a HTTP GET from my TypeScript application, which is AngularJS-based:

$http.get("http://localhost/books/0743273567")
   .success((book: Book) => { ... });

So that I am able to use the strongly-typed nature of TypeScript, I find myself hand-coding the following typescript interface:

module com.acme.library {
  export interface Book {
      author: com.acme.library.Author;
      title: String;
  }
}

As a result, I have to maintain two copies of this same interface -- which is cumbersome at best. This gets particularly nasty, as I'd like to have the same javadoc/jsdoc comments on both interfaces, which involves a whole heap of copy&paste.


I would like to find a mechanism for automating this process.

Java is my main development language. As such, I'd like to find some tool which is capable of converting from the Java interface declaration (via the reflection API?) to the relevant TypeScript interface.

The only tool I have discovered in this domain is the NPM package ts-java. However, this is far too heavyweight for my use-case. It adds methods from the Object hierarchy to each interface, e.g. hashCode(), wait(), getClass(), etc.

like image 229
jwa Avatar asked Sep 08 '15 07:09

jwa


4 Answers

You can use typescript-generator as larslonne mentioned. It generates TypeScript interfaces from Java JSON classes. Some features you may find useful:

  • Maven and Gradle plugin (can also be invoked directly from Java)
  • Jackson 1 and Jackson 2
  • collections, enums, inheritance, generics
  • Javadoc comments to JSDoc comments
  • detailed documentation (README, Wiki, Maven plugin)
  • releases in Maven central repo

Here is example how to use it from Maven:

<plugin>
    <groupId>cz.habarta.typescript-generator</groupId>
    <artifactId>typescript-generator-maven-plugin</artifactId>
    <version>1.25.322</version>
    <executions>
        <execution>
            <id>generate</id>
            <goals>
                <goal>generate</goal>
            </goals>
            <phase>process-classes</phase>
            <configuration>
                <jsonLibrary>jackson2</jsonLibrary>
                <classes>
                    <class>com.acme.library.Book</class>
                </classes>
                <outputFile>target/rest.d.ts</outputFile>
                <outputKind>module</outputKind>
            </configuration>
        </execution>
    </executions>
</plugin>

Edit: Run it using mvn process-classes or using later phase like mvn install.
You can also pull <configuration> element two levels up and run mvn typescript-generator:generate.

Edit: I am the author of typescript-generator.

like image 92
Vojta Avatar answered Oct 17 '22 01:10

Vojta


I am currently working on a project with the same setup as yours: a Java API, and a Typescript web application.

We are using cz.habarta.typescript-generator.typescript-generator-maven-plugin to generate the .d.ts files when we build the API. The definition files are then packaged as an artifact with <type>d.ts</type>, using the org.codehaus.mojo.build-helper-maven-plugin. Lastly, the artifact is imported as a dependency in the web application, where the definition files are unpacked into the target directory.

This setup requires that you use maven for the web application, which isn't ideal, but it's a small price to pay for automatically generated definition files.

like image 33
lalo Avatar answered Oct 17 '22 00:10

lalo


I had great luck with Amdatu TypeScript Generator

It can run in Gradle or standalone from the terminal (I used terminal, so that's what these instructions here are)

Simply clone the repo, run ./gradlew to build it.

To execute it, I had to deviate a little from their instructions because there was no entry point in the jar (you wouldn't have this issue if you use a gradle build, because it would specify the entry class).

I used:

java -cp build/libs/org.amdatu.typescriptgenerator-1.0-SNAPSHOT.jar org.amdatu.typescriptgenerator.standalone.TypeScriptGeneratorStarter

It should then complain that there isn't a typescript.settings.json file, which it's expecting in the directory you are running the command from.

I'll include my own example because the linked repo's example settings file is a little unclear:

{
  "folder" : "/projectsfolder/project",
  "classFolder" : "target/classes",
  "output" : "typscriptOutputDirectory",
  "baseFolder" : "",
  "clearOutput" : false,
  "packages" : [
    ".*regexforwhatpackagesinsidetargetprojectshouldbeturnedintotypescript.*"
  ],
  "excludePackages" : [ ],
  "excludePattern" : [ ],
  "types" : { },
  "mapping" : { },
  "enumType" : "class",
  "classType" : "interface",
  "classPath" : [ ]
}

The most important fields in the settings are:

  • folder is where your already built project is
  • classFolder is where this generator will look inside that folder for compiled java classes
  • output is the directory where the typescript definition files will be placed, relative to where you're executing the generator
  • packages is a java regex for what packages should be turned into TypeScript definitions
like image 3
Ryan Weir Avatar answered Oct 17 '22 02:10

Ryan Weir


I created a new project with the goal to keep as simple as possible the transpiling process: JavaModel-Converter

It works with the ide or simply by command line executing the jar present into dist folder.

All you need is to put your java model in the desired folder and to start transpile process.

I added also Angular style support.

Let's open issues if you have requests!

Theoretically my project is a general java model converter, but actually, only Typescript transpile is supported

like image 1
firegloves Avatar answered Oct 17 '22 00:10

firegloves