Kotlin / dukat

Converter of <any kind of declarations> to Kotlin external declarations
554 stars 44 forks source link

Proposal to handle Partial #147

Open altavir opened 6 years ago

altavir commented 6 years ago

I just installed latest version and saw that ts2kt still does not handle partials. One could ignore TypeScript, but the situation when a lot of fields in the JS object are optional is fairly frequent. I want to propose one of the possible ways to handle it without modifying something in the language itself.

Consider generated interface

external interface Point {
    var x: Number
    var y: Number
    var z: Number
}

I propose to check the whole definition to see if this class is used as Partial somewhere, generate something like that instead:

fun Point(builder: Point.()->Unit): Point{
    return object : Point{
        override var x: Number? = null
        override var y: Number? = null
        override var z: Number? = null
    }.apply(builder)
}

external interface Point: Partial {
    var x: Number?
    var y: Number?
    var z: Number?
}

Partial here is a marker interface for future reference.

Then object construction will look like this:

val myPoint = Point{ x = 1, y = 2}

The drawback is that one enforces nullability on all fields, but obviously if partial is used anywhere, it is indeed nullable.

Miha-x64 commented 5 years ago

FYI, significantly different Partial sample for Kotlin suitable for statically typed languages where everything is a reference.