Typafe wrapper around javascript object in scala.js

I want to write a scala.js wrapper around a javascript library that has an object that can be instantiated like this:

new Point({x: 10, y: 12})

      

It seems to be simple. I would like to have a coordinate case class and a wrapper around the point.

case class Coord(x: Int, y: Int)
class Point(coord: Coord) extends js.Object

      

This clearly does not work as the case class does not translate to an object literal. I could of course get rid of the Case class and pass js.Dynamic.literal to the constructor instead, but that's not very typical.

What other option do I have? Should I write a higher level wrapper that takes a coordinate and converts it to an object literal before passing it to a Point object?

+3


source to share


1 answer


You have several options:

Option object

trait Coords extends js.Object {
  def x: Int = js.native
  def y: Int = js.native
}

class Point(coords: Coords) extends js.Object

      

and a factory type for Coords

. Details in this SO post



Factory dot / Top-level wrapper

case class Coords(x: Int, y: Int)

object Point {
  def apply(coords: Coords): Point = new Point(
    js.Dynamic.literal(x = coords.x, y = coords.y))
}

      

Interpret the Case class as an Option object

trait PointCoords extends js.Object {
  def x: Int = js.native
  def y: Int = js.native
}

@JSExportAll
case class Coords(x: Int, y: Int)

val c = Coords(1, 2)
new Point(js.use(c).as[PointCoords])

      

+4


source







All Articles