dart-lang / web

Lightweight browser API bindings built around JS static interop.
https://pub.dev/packages/web
BSD 3-Clause "New" or "Revised" License
135 stars 23 forks source link

Preferred way to convert a `JSAny` #310

Closed arnaud-secondlayer closed 1 month ago

arnaud-secondlayer commented 1 month ago

HTMLDivElement function innerHTML returns JSAny. I'd like to convert it to a darlang String.

What is the preferred solution? I can think of two, but there could be others as well.

final str =  (div.innerHTML as JSString).toDart;
final str =  div.innerHTML.toString();

My criterion for preferred solution would probably be that the generated javascript is the simplest possible.

srujzs commented 1 month ago

They should both work, but the first one is preferred so that you're not relying on the behavior of toString. As for code size/performance, they should be similar e.g.

// dart2js
A._asString(t1._as(_this.innerHTML)) // first
J.toString$0$(t1._as(_this.innerHTML)) // second

Both do a typeof check but the second one goes through roughly an extra call to intercept the type. In dart2wasm, they should also be similar in performance/code-size (one interop call to convert a JS string to a Dart String)

For context on why this needed to be a JSAny: this API can possibly return a TrustedHTML instead of a string.

arnaud-secondlayer commented 1 month ago

Thanks