how can I ensure that a method receive a javascript literal (js.dynamic.literal). It is not a type but it is js.Dynamic so it can be anything. Thanks
Asked
Active
Viewed 131 times
1 Answers
0
There is no way, the Scala.js type system is able to enforce that. It also seems a quite arbitrary restriction to me.
A couple of things come to mind:
Literally what you are asking for:
Use a macro to enforce that the argument to your method is a (JS) literal. This is what you also have to do, if you want to check if its, for example, a String literal.
Note that not every call to js.Dynamic.literal
produces a JS object literal at the end. Consider:
val mySeq = Seq("a" -> 1, "b" -> 2)
js.Dynamic.literal(mySeq: _*)
What you might want to be doing:
If you are creating facade types for a library and are creating option objects, we recommend the following pattern:
def myMethod(opts: MyMethodOptions): Unit = js.native
trait MyMethodOptions extends js.Object {
val debug: Boolean
val fast: Boolean
}
object MyMethodOptions {
def apply(debug: Boolean = false, fast: Boolean = false): MyMethodOptions =
js.Dynamic.literal(debug = debug, fast = fast).asInstanceOf[MyMethodOptions]
}
Invoke like this:
myMethod(MyMethodOptions(fast = true))
That way the cast to MyMethodOptions
is contained in the companion, so the type unsafe part is minimal and contained.

gzm0
- 14,752
- 1
- 36
- 64
-
Hi, thanks for your answer. I'm doing a facade for sigma.js library. What I want is insure in compilation time that an object that has at less a field, for example to add a node to the graph it have to has an "id" field or the function fail. How can I do that? – gilcu2 Apr 28 '15 at 13:22
-
Just how I have shown in the second part of my answer: Make a facade option trait for it and use it. – gzm0 Apr 28 '15 at 17:48