40

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.

0

6 Answers 6

36

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.

Sign up to request clarification or add additional context in comments.

6 Comments

I tried to run the sample project but I got the following error: Description Resource Path Location Type Could not find artifact cz.habarta.typescript-generator:typescript-generator-maven-plugin:jar:1.7-SNAPSHOT pom.xml /test line 1 Maven pom Loading Problem
@DorCohen replace 1.7-SNAPSH‌​OT with latest version in maven central repository repo1.maven.org/maven2/cz/habarta/typescript-generator/…. Currently it is 1.10.220.
When I'm updating to to 1.10.220 I;m getting the following error: Plugin execution not covered by lifecycle configuration: cz.habarta.typescript-generator:typescript-generator-maven-plugin:1.10.220:generate (execution: generate, phase: process-classes)
@DorCohen it seems this is some problem with your maven build configuration (pom.xml). Can you send me your pom.xml file? You can fill issue on github and I will try to help you.
@KevinGleeson it's not possible, in single run it generates one file/module
|
4

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.

Comments

3

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

Comments

1

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

Comments

0

You can use Script4J that is a set of libraries to code in TypeScript using Java API. Although this is a new project it can be useful.

Comments

0

Have been making a new annotation processor SharedType, used in my major web services to convert dozens of types. Developed it because I want support for:

  • constants
  • generics

But it has more, e.g., intuitive configurations, and more features to come.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.