How will Kotlin handle Union types from JavaScript/TypeScript?


#1

Many JavaScript libraries have methods with parameters that can be 1 of 2 or more types.
TypeScript calls these Union types.

The TypeScript type definition for JQuery has over 100 such cases.
The TypeScript type definition for React has dozens of such cases (e.g. ‘type Key = string | number;’).

I’ve heard that Kotlin will consume TypeScript’s type definitions in some way.

How will Kotlin represent React’s ‘Key’ (from the example above)?


#2

In JS and TS in most cases union types used as the alternative to overloading, so in the near future, we going to use overloading for that when it possible.
Also,​ we think about providing the additional way to specify union types for native declarations.


#3

It looks like there are many issues with that approach.

  1. Kotlin’s support for default values for method parameters allows us to have many fewer overloads than Java code. This approach moves us in the other direction.

  2. This approach has a combinatorial explosion. If you have 2 parameters on your method that are each Union types, you need to generate all possible combinations of the argument types.

  3. What about when the method return type is a Union type?

  4. What about when fields have a Union type?

  5. What about when data has a Union type?

Perhaps I’m missing something, but it looks to me like native support for Union types is the cleanest way to address these issues.

When you look through the type definitions in DefinitelyTyped, you can see that Union types are common.


#4
  1. I think it’s good enough since it’s only about native/external declarations.

  2. it’s the reason why I said: “when it possible”.

    1. it’s the reason why we think about alternative solutions
  3. could you please clarify what do You mean?

it looks to me like native support for Union types is the cleanest way to address these issues.

It’s another possible solution and I agree that it probably is the better solution, but it requires more time to design and implement it. And we need more good use cases to do it.


#5

I thought I remembered a KEEP about union and intersection types, but can now find no traces of it. Anyone know where it went?


#6

Are you referring to this thread? Union types


#7

No I was thinking of something that was on the KEEP github repository. Maybe it wasn’t specifically about intersection and unions, but something about the type system?


#8

Sorry, ignore #5.