If I want to access an external javascript variabl...
# javascript
j
If I want to access an external javascript variable from my code, is
js("foo") as Type
the best option? What about going the other way around, do I need to generate
js("foo = [js string representation]")
? This is easy for primitives but more tedious for other objects
e
Copy code
external var foo: Type
j
ah, thanks. wasn't sure from docs if that would work
I can't figure out how to get this to work with a map
Copy code
<script>
        let foo = 0.0
        let bar = {}
    </script>
Copy code
external var foo: Double
external var bar: MutableMap<String, Any>
Copy code
foo = 1.0
bar["test"] = "a"
foo works as expected
bar says
Copy code
Uncaught TypeError: tmp0_set_0.put_3mhbri_k$ is not a function
e
MutableMap
is a Kotlin type, but
{}
in JS is not
Copy code
external val bar: dynamic
bar["test"] = "a"
j
wow, black magic 🙂 that works
b
external val bar: Json It's safer and represents js object types
j
perfect, thanks
e
dynamic
lets you write
bar.test = "a"
just like you can in JS, which you could consider a plus and/or a minus
j
that makes sense
b
Dynamic type is basically an escape hatch to tell the compiler to completely drop the type safety. It's necessary to handle some janky js voodoo interop, but in general should be avoided as much as possible (otherwise you're better off to just coding in plain js)
Not sure if you've seen it yet, but I've written an article that covers most of what one needs to know when interoping with js https://dev.to/mpetuska/js-in-kotlinjs-c4g
j
Reading now. Thanks!