Ts2kt: Union & Intersection types?

Hi guys,
I’m looking a bit deeper trying to understand if Kotlin for JS is ready for production use cases.

Specifically, I’m using ts2kt to convert TypeScript definitions of some supporting React libraries such as Redux, Apollo etc.

Unfortunately, these definitions are plagued by union and intersection types (as well as Partial), and they seem very common in JavaScript/TypeScript (http://www.typescriptlang.org/docs/handbook/advanced-types.html). For example, every library will try to inject something into Props. Of course, all these libraries could be redesigned not to use such types, but I feel JavaScript/TypeScript is far along that path and such thing will never happen.

Example TypeScript: https://github.com/apollographql/react-apollo/blob/master/src/types.ts

Given that Kotlin does not support intersection/union types, is there any practical solution to this problem? I’m really interested to hear your thoughts. Thanks!

1 Like

cc @bashor

Often the problem is the “magic overloading” in javascript functions that results in typescript specifying a union parameter type. Ts2kt is certainly not optimal in the translation of this, but it could be correctly translated as a set of overloads for the different parameters (taking care to make resolution work correctly - default values are another issue).

Javascript uses duck typing so you can be quite “flexible” in your Kotlin hierarchy including adding “virtual” interfaces.

Union return types could be Any or a common superinterface defined for that purpose

Intersection type parameters can be expressed as generic type parameters with multiple requirements (I haven’t checked that it is an acceptable JS external - but within Kotlin it is valid).

For intersection return types it is possible to just define an interface that is the union of it constituents.

1 Like