jsweet icon indicating copy to clipboard operation
jsweet copied to clipboard

Make @Replace work with fields

Open nedtwigg opened this issue 3 years ago • 2 comments

The TypeScript handbook gives this example, which also works with interfaces as such:

interface NetworkLoadingState {
  state: "loading";
}

interface NetworkFailedState {
  state: "failed";
  code: number;
}

To generate something like this with jsweet, I tried this in the live sandbox

@jsweet.lang.Interface
public class NetworkLoadingState {
  public String state = "loading";
}

but I get field 'state' cannot be initialized in interface 'NetworkLoadingState'. I tried to see if I could do something like @jsweet.lang.Replace("state: \"loading\""), but Replace can only be applied to methods, not members...

nedtwigg avatar Aug 14 '20 07:08 nedtwigg

Hello @nedtwigg Thanks for your question. I think String Types is what you are looking for.

lgrignon avatar Aug 14 '20 07:08 lgrignon

Ah, thanks. For my usecase, we have a server written and executing in Java. We use jsweet to transpile datatypes to typescript. This makes it very easy to have strongly-typed communications between javascript clients and the server, since they're using the same data.

The nice thing about String state = "loading" is that our java JSON serialization can handle it just fine, but it takes quite a bit of fiddling to make @jsweet.lang.StringType public interface loading {} work. It would be great if @jsweet.lang.Replace could be used for fields, instead of just methods.

The @jsweet.lang.StringType mechanism is a very clever way to mimic the behavior of the Typescript type system within Java. But our goal is more about data portability, and generating code which is idiomatic in both Java and Typescript, rather than tricking the Java typesystem to behave like Typescript. Since the two languages have different type systems, it seems unavoidable that there will be cases where the user wants to take manual control over the typescript definition.

nedtwigg avatar Aug 14 '20 18:08 nedtwigg