Problem with declarations added by kotlin-js

I’m tinkering with Kotlin-JS and trying to use google charts and basically doing an example like this one in Kotlin:

Which requires loading the charts library like shown here:

So just the first step of that process I am running into an issue where Kotlin is adding some declarations that fail because the values are not available yet.

So here is the first part of the Kotlin code to just load the chart library and create a query object:

fun main(args: Array<String>)
{
    google.charts.load("current", js ("{'packages':['corechart']}") as Any )
    google.charts.setOnLoadCallback(::drawChart)
}

fun drawChart()
{
    val query = google.visualization.Query(URL)

Which is using some header files generated using ts2kt from typescript for google charts from the DefinitelyTyped library.

The issue I am having is that in the generated javascript Kotlin is adding a declaration like this near the top so that it presumably does not have to use fully qualified name later:

var Query = google.visualization.Query;

But google Charts is loaded asynchronously and it adds google.visualization to the namespace and it is not guaranteed to be there until the call back (drawChart in this case) is called. So the java script is failing on the declaration of Query variable because google.visualization isn’t there yet.

How can I work around this?

No idea how to configure ts2kt but one hacky way to “fix” this is to load kotlin.js/app.js etc dynamically with js wrapper within drawChart callback. Just insert script tags with js.

ts2kt is not a problem. It worked fine other than actual problems with the source typescript (not declaring constructors on subclasses).

I am not very knowledgeable on Javascript so not sure how to do what you are suggesting.

OK I managed to pull the google charts load into the html page and not load my kotlin generated JS until drawChart is called by putting this in HTML:

    <script type="text/javascript">
        google.charts.load('current', {'packages':['corechart']});
        google.charts.setOnLoadCallback(drawChart);

        function drawChart()
        {
            var scriptTag = document.createElement('script');
            scriptTag.src = 'myJavascriptFile.js';
            document.body.appendChild(scriptTag);
        }
    </script>

I don’t think there is a much better solution. I guess we didn’t anticipate this use case.

I’ve create an issue to track this problem: https://youtrack.jetbrains.com/issue/KT-23561