Using existing js libraries with generated code from ts2kt

Hi.

I’ve been trying to use ChartJs through KotlinJS.
First I used ts2kt (GitHub - Kotlin/ts2kt: ts2kt is officially deprecated, please use https://github.com/Kotlin/dukat instead. // Converter of TypeScript definition files to Kotlin external declarations) to get type bindings from Typescript (https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/chartjs) easily to Kotlin.

Excerpt of generated Kotlin kode:

external interface Chart {
    fun Line(data: LinearChartData, options: LineChartOptions? = definedExternally /* null */): LinearInstance
    fun Bar(data: LinearChartData, options: BarChartOptions? = definedExternally /* null */): LinearInstance
    ...
}

Looking at the test code in DefinetelyTyped chartjs, the chartjs is easily used from Typescript like this:

var myChart = new Chart(ctx).Bar(data, options) 

However, the same is not as easy with Kotlin. I’ve been trying to something like this

val myChart = object : Chart(ctx) {
   ...
}

…but that does not work out good as

  • the interface Chart (clearly) does not have a constructor
  • it requires me to implement every method in my anonymous instance of Chart

Does anyone have better experience mapping existing js-libraries written like this? Is ts2kt leading me in the wrong direction? Should I change the generated kotlin code (maybe, from interface to class)? or is there a easier way to overcome this with using the generated kotlin code as is?

try

val chart = js("new Chart(ctx)") as Chart
chart.Bar(data, options)

don’t forget to actually include chartjs.js itself

You can wrap this whole thing into a factory function. You could also try to see whether changing the external interface by an external class works (and add the constructor definition).

Overall I find that ts2kt often does not produce optimal externals, in particular with overloaded functions as you find in for example jquery.

A late thanks for the input @Konstantin-Khvan and @pdvrieze

Unfortunately, I did not really find a nice solution using your tips, not saying it was anything wrong with the suggestions, just was not able to make it work. So I gave it up for now.

In time my plan is to study this page further: https://kotlinlang.org/docs/reference/js-interop.html and experiment creating a bridge manually.

Anyway, thanks!

As I see (examples and declarations) replacing external interface with external class for Chart should work, doesn’t it?