ScalaJS: How to create option [A] from JS?

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.

+4
source share
1 answer

Short answer: you cannot. However, there are two problems with your problem.

Providing global functions for building Someand selection None(suboptimal)

Add such an object to 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)
}

Now you can use this factory from JS to create parameters:

var none = some.pack.OptionFactory.none()
var some = some.pack.OptionFactory.some(5)

Directly output the API managing js.UndefOr(recommended)

, JS Option s, JS-friendly API Scala.js. , , , - :

def foo(opt: Option[Int]): Unit = ???

JS-:

@JSExport
def foo(opt: js.UndefOr[Int]): Unit = foo(opt.toOption)

JS undefined None Some[Int], :

scalaJSObj.foo(undefined)
scalaJSObj.foo(5)
+6

Source: https://habr.com/ru/post/1611108/


All Articles