Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for sealed classes #4

Open
bernerbrau opened this issue Mar 27, 2018 · 3 comments
Open

Support for sealed classes #4

bernerbrau opened this issue Mar 27, 2018 · 3 comments

Comments

@bernerbrau
Copy link

Would be nice to see sealed class to union type support, e.g.

sealed class Thing {
  data class ThingOne(val value: String): Thing()
  data class ThingTwo(val otherValue: Int): Thing()
}

Would compile to:

interface ThingOne {
  value: string;
} 
interface ThingTwo {
  otherValue: number;
}
type Thing = ThingOne | ThingTwo;
@ntrrgc
Copy link
Owner

ntrrgc commented Mar 27, 2018

The problem is that TypeScript unions and sealed class don't map as much as I'd like.

The most striking difference is that sealed class are abstract classes, whereas named unions are not, and therefore they need to be omitted in the extends clause.

Also, sealed children may be defined either as a nested classes or separate classes in the same file (since Kotlin 1.1). Unfortunately there is no way to query sealed children in the later case.

bernerbrau pushed a commit to bernerbrau/ts-generator that referenced this issue Mar 27, 2018
bernerbrau pushed a commit to bernerbrau/ts-generator that referenced this issue Mar 27, 2018
@bernerbrau
Copy link
Author

bernerbrau commented Mar 27, 2018

OK, so, check my PR - turns out sealed classes are more complicated than I initially thought. It also generates code (in a separate output property) to check if a JS object has a matching type; when working with union types this seemed necessary to implement. I did have to refactor the class visitor pattern a bit to make this work.

It may be more than you're looking for, and I haven't included unit tests, but it seems to work well on our Kotlin class model. I can add in some UTs if that helps.

It's true that there's no way using vanilla Kotlin or Java reflection to scan for subclasses. So I used the Reflections library to scan for subclasses; Reflections does some basic classpath scanning to accomplish this.

I'm also working on a gradle plugin to generate this on the fly for mixed-sourceset Kotlin and Node projects and/or multimodule projects.

@bernerbrau
Copy link
Author

I've added in UTs for two basic typedef cases. I had to refactor the factory code that builds TypeScriptDefinitions since the union type made it much more complex.

The actual generated code that does type checking still needs UTs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants