scala-js-dom
scala-js-dom copied to clipboard
Literal types
I find myself doing this a lot:
dom.document.createElement("div").asInstanceOf[dom.raw.HTMLDivElement]
It would make sense to have extensions for most of the dom.raw
package.
i have code for this lying around somewhere.
way too soon afterwards though, code like this began annoying me:
import tags._
val x = div()
x.id = "foo"
x.className = "message"
x.textContent = "hello"
so that preceived gain was not as big as i imagined.
If you import org.scalajs.dom.html._
then there are shorter type aliases for most elements. You example would become dom.document.createElement("div").asInstanceOf[Div]
.
I just live with that, although I'm not sure how users would know to import that package.
Thinking about it, in this case, it would be nice to be able to do: document.createElement[Div]
. HTMLDivElement doesn't currently know the corresponding element name is 'div' though.
that could easily be done with a simple type class
Another approach: https://blog.ramnivas.com/technology/2020/02/05/literal-types-to-simplify-code.html.
Wow, the literal types approach is super clean:
def createElement(tagName: "script"): HTMLScriptElement = js.native
def createElement(tagName: "a"): HTMLLinkElement = js.native
...
I understand why this repo wouldn't want custom createElementX
methods – those wouldn't match the underlying JS API and would require an implementation. But it seems that literal types address this concern, the API would match the JS API, and would not require any implementation to be written, just the interfaces.
These new methods would only be available in 2.13+, but maybe that's good enough?
I like the idea of literal types too, let's keep this on our radar :)