Alban Dericbourg
Alban Dericbourg

Reputation: 1634

JavaScript object as function parameter

I'm writting a function transpiled with Scala.js that should accept any random JavaScript object.

Ex:

// 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" } });

However, I can't find the input type that matches it.

Note (if it helps giving a direction for the answers): these objects have, in the real life, an expected schema but it cannot be created as JS object generated from Scala.js since it comes from another consumed service.

Upvotes: 1

Views: 276

Answers (1)

gzm0
gzm0

Reputation: 14842

Since the objects have an expected schema, its probably easiest to define a facade type:

@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))
}

Upvotes: 1

Related Questions