Has anyone tried code conversion between Kotlin and TypeScript? Any libraries or starting points to recommend?
Our backend is in Kotlin and clients in TypeScript. We are primarily interested in converting declarative stuff i.e. data classes to type
and constant structures (Kotlin objects to JS objects). The direction should be Kotlin → TS.
Code conversion inside functions is not important right now.
Thanks
The Kotlin/JS 1.4 compiler can output TypeScript declarations usable from TS. There are limitations tho.
Have a look here for more informations: https://kotlinlang.org/docs/reference/js-ir-compiler.html#preview-generation-of-typescript-declaration-files-dts
Of course to share code you have to create a common Gradle module with Kotlin/Multiplatform with 2 targets (JS Browser and JVM) and configure the output of the JS build according to the state of your frontend. To do so you probably gonna have to deal with the complexity of Gradle itself, but it is worth the fatigue!
2 Likes
Hey @lamba92 thanks for your answer!
Do you maybe know how the generated definitions will look like for sealed classes? I’m wondering if you had the chance to try it out and possibly provide me an example for a sealed class. I’d like to see if it’s worth the effort vs. just coming up with our own generator which is more compatible with our existing frontend.
Well do not expect such advanced (and cool) Kotlin features to be translated to TS/JS since there is no actual way to do it! If your frontend is not in Angular, consider going full Kotlin/JS since everything else can be done entirely in Kotlin! If you go Kotlin fullstack, sharing code becomes really easy.
Also typescript definitions are super experimental!
This is already a mature project and converting it is out of the question. If I could choose I would actually go the other way (converting backend to TS 
We actually have an already working serialization from data & sealed classes to JSON and matching TypeScript types, it’s just that we have to manually convert the type definitions themselves. Time to do some coding!
1 Like
I did some work on integrating kotlin and typescript. Documented here. Building Web Applications with Kotlin and TypeScript | by Dr. David H Akehurst | JavaScript in Plain English
I suggest, not converting kotlin to typescript, rather use the kotlin generated JS code from typescript.
1 Like
This not very optimal. This way you’ll loose TypeScript’s main benefit - types. Types definitions is the proper way to do it.
About use of Kotlin’s sealed classes I would say that from TypeScript type definition point of view it doesn’t really matter. Kotlin adds some boilerplate code to those classes, but for TypeScript it is irrelevant.
If you read the post, you will see that I do address that issue.
My approach keeps the types, and they are useable from Typescript…
1 Like