dart-archive / js_facade_gen

Generates package:js Javascript interop facades for arbitrary TypeScript libraries
Apache License 2.0
161 stars 29 forks source link

Idea: auto-wrap callbacks in `allowInterop` #78

Open ditman opened 4 years ago

ditman commented 4 years ago

In the same way we're wrapping returned Promises in promiseToFuture, so they can be directly used in Dart as Futures, I think we could also wrap callbacks passed as parameters with allowInterop so the users' code in Dart doesn't need to.

On something like:

then(onInit: (googleAuth: GoogleAuth) => any, onFailure?: (reason: {error: string, details: string}) => any): any;

This generates:

external dynamic then(dynamic onInit(GoogleAuth googleAuth),
    [dynamic onFailure(dynamic /*{error: string, details: string}*/ reason)]);

Which in Dart you need to use as:

auth.then(allowInterop((GoogleAuth googleAuth) {
  // onSuccess
}), allowInterop((dynamic reason) {
  // onError
}));

It'd be way more pleasing (and easier to read) to be able to just do:

auth.then((GoogleAuth googleAuth) {
  // onSuccess
}, (dynamic reason) {
  // onError
});

I understand the generator itself can't know if there's going to be a negative performance impact from calling allowInterop automatically, but it'd be cool if there was a flag to control this behavior on a per-usage basis.