JS Interop Poser

I’m getting a dynamic type back from JS, I know its a JSArray and I want it to be a list of Strings, this conversion works -

List<String> keyList = ((res.keyList as JSArray).toDart).cast<String>();

As you can see I make it a JSArray type so I can toDart it and cast its elements to String’s.

This works but intuitively it looks fiddly and overkill for what I’m doing, is there a better way to do this?

1 Like

That looks ok. Why do you think its overkill?

I was sort of expecting to do this -

toDart<String>();

As in ‘convert to List and cast the elements to String’ thus avoiding the separate cast. You can cast the elements but only to a type derived from JSAny e.g. JSString, not String I think.

Note that the original code is somewhat incorrect or at least slightly unportable -if you want to target Wasm as well as JS. When you target JS JSString is pretty much the same as String so you can get away by not applying toDart to the elements. However when you target Wasm that is not the case. So you need to make sure to perform conversion deeply:

final keyList = (res.keyList as JSArray<JSString>).toDart.map((s) => s.toDart).toList();
1 Like

Thanks for the insight.

So does this mean I should assume WASM is being used all the time, i.e. the example you give works with both JS and WASM, mine (may)only work with JS otherwise bugs may occur by any users targeting WASM only that I won’t see if I only target JS.

So does this mean I should assume WASM is being used all the time

Yep, I would recommend developing under this assumption.