scala-js/scala-js-dom

Literal types

Opened this issue · 7 comments

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.

Grogs commented

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.

Grogs commented

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

raquo commented

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 :)