scala-js-dom icon indicating copy to clipboard operation
scala-js-dom copied to clipboard

Literal types

Open MasseGuillaume opened this issue 7 years ago • 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.

MasseGuillaume avatar Aug 23 '17 10:08 MasseGuillaume

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.

ritschwumm avatar Sep 03 '17 10:09 ritschwumm

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 avatar Nov 13 '17 19:11 Grogs

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.

Grogs avatar Nov 13 '17 19:11 Grogs

that could easily be done with a simple type class

ritschwumm avatar Nov 13 '17 19:11 ritschwumm

Another approach: https://blog.ramnivas.com/technology/2020/02/05/literal-types-to-simplify-code.html.

ramnivas avatar Feb 07 '20 20:02 ramnivas

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?

raquo avatar Feb 07 '20 22:02 raquo

I like the idea of literal types too, let's keep this on our radar :)

armanbilge avatar Aug 11 '21 02:08 armanbilge