I have a ScalaJS function that I would like to call from JS, that has an Option[String] parameter. I could not figure out how to create Some[String] and None[String] from JS.
Short answer: you can't. There are two solutions to your problem, though.
Some
s and retrieving None
(suboptimal)Add an object like this in your Scala.js codebase:
package some.pack
@JSExport
object OptionFactory {
@JSExport
def none(): None.type = None
@JSExport
def some[A](value: A): Some[A] = Some(value)
}
You can now use that factory from JS to create options:
var none = some.pack.OptionFactory.none()
var some = some.pack.OptionFactory.some(5)
js.UndefOr
(recommended)Instead of forcing JS to manipulate Option
s, you can expose a JS-friendly API directly from your Scala.js class. Suppose your function that you want to expose is something like:
def foo(opt: Option[Int]): Unit = ???
You can instead, or in addition, export the following JS-friendly version:
@JSExport
def foo(opt: js.UndefOr[Int]): Unit = foo(opt.toOption)
which will allow JS to simply use undefined
for None
and any integer for Some[Int]
, e.g.:
scalaJSObj.foo(undefined)
scalaJSObj.foo(5)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With