JavaScript对象作为函数参数

时间:2016-08-11 08:56:16

标签: scala.js

我正在编写一个用Scala.js编译的函数,它应该接受任何随机的JavaScript对象。

例如:

// This has been transpiled using Scala.js
var my_service = new com.myself.Service();

// This is plain JavaScript 
var result1 = service({ hello: "yolo" });
var result2 = service({ whatever: "ok", really: { yes: "right", no: "don't" } });

但是,我找不到与之匹配的输入类型。

  • 获取此类内容的Scala函数签名是什么?
  • 它可以轻易用作“Scala / JS案例类”吗?

注意(如果它有助于给出答案的方向):这些对象在现实生活中具有预期的模式,但它不能被创建为从Scala.js生成的JS对象,因为它来自另一个被消耗的服务。

1 个答案:

答案 0 :(得分:1)

由于对象具有预期的模式,因此最容易定义外观类型:

@js.native
trait Args extends js.Object {
  val hello: js.UndefOr[String]
  val whatever: js.UndefOr[String]
  val really: js.UndefOr[ReallyArgs]
}

@js.native
trait Really extends js.Object {
  val yes: String
  val no: String
}

def myMethod(args: Args): Unit = {
  println(args.hello)
  println(args.really.map(_.yes))
}
相关问题