Skip to content
This repository has been archived by the owner on Nov 6, 2019. It is now read-only.

Better union support #41

Closed
ScottPeterJohnson opened this issue Mar 20, 2017 · 3 comments
Closed

Better union support #41

ScottPeterJohnson opened this issue Mar 20, 2017 · 3 comments

Comments

@ScottPeterJohnson
Copy link

ScottPeterJohnson commented Mar 20, 2017

Currently type unions in return types get converted to "dynamic". This is pretty unsafe. I'm proposing a safer method, with some Kotlin code attached.
Given a function that returns string|number, generate:

external fun someFunction() : StringOrNumber;
external class StringOrNumber
inline fun <T> StringOrNumber.destructure(
		onString : (String)->T,
		onNumber: (Number)->T
) : T{
	if("string".equals(jsTypeOf(this))){
		return onString(this.unsafeCast<String>())
	} else if("number".equals(jsTypeOf(this))){
		return onNumber(this.unsafeCast<Number>())
	} else {
		throw IllegalStateException("Value is neither type 'string' nor type 'number': ${this}")
	}
}

The inline function would have to be generated in a separate Kotlin file, but it could make for safer code, which might improve the quality of the converter itself. We'd need a type discriminant per type, however. Some libraries define their own type discriminants, but following a basic primitive type/known disjoint properties method could be helpful, especially with string literal types.
I can try to generate a proof of concept implementation if this seems okay.

@bashor
Copy link
Member

bashor commented Mar 30, 2017

Sorry for the delay!
It looks too verbose to me. One possible solution that we discussed is using an annotation on the type and write some checker in Kotlin JS frontend.

@ScottPeterJohnson
Copy link
Author

Oh, that solution actually does sound better. I'll close this issue in favor of that.

@bashor
Copy link
Member

bashor commented Mar 31, 2017

Anyway, thank you for the request

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

No branches or pull requests

2 participants