Reputation: 303
I am trying to create a scala.js facade for an existing javascript library. This one particular function has the following signature:
def something(command: String) = js.native
Now the issue is that in the actual javascript library this method returns a String for one value of command and returns a JQuery for another value of command. I am not sure what to make the return type for this method. I was thinking of keeping it as js.Any and then the user would have to convert it to the respective type using asInstanceOf, but I think it can be handled in a better way.
Any suggestions?
Upvotes: 2
Views: 227
Reputation: 2659
Personally, I would probably wrap this as multiple strongly-typed functions in Scala, wrapping around the specialized Strings.
For an example, see the Manifest facade that I built for Querki. That has an internal facade that just describes the literal call:
@js.native
trait ManifestFacade extends js.Object {
@JSName("manifest")
def manifestInternal(cmd:String, params:js.Any*):Any = js.native
}
That isn't intended for application use, though. Instead, there is a wrapper layer around that, with functions that are more precise, such as:
class ManifestCommands(manifest:ManifestFacade) {
def manifestList():dom.Element = manifest.manifestInternal("list").asInstanceOf[dom.Element]
def manifestGetOptions():js.Dictionary[js.Any] = manifest.manifestInternal("option").asInstanceOf[js.Dictionary[js.Any]]
def manifestGetOption(name:String):Any = manifest.manifestInternal("option", name)
}
There is an implicit conversion from ManifestFacade
to ManifestCommands
. (This is oldish code; nowadays, I would write ManifestCommands
as an implicit class.)
It's a bit of extra effort upfront, but this allows the application code to work at a nice, strongly-typed level, without worrying about the way the various commands are really calling a wildly polymorphic function under the hood.
Upvotes: 2