Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[js inteorp] asA to correspond to isA #56957

Open
parlough opened this issue Oct 24, 2024 · 1 comment
Open

[js inteorp] asA to correspond to isA #56957

parlough opened this issue Oct 24, 2024 · 1 comment
Labels
area-web Use area-web for Dart web related issues, including the DDC and dart2js compilers and JS interop. web-js-interop Issues that impact all js interop

Comments

@parlough
Copy link
Member

parlough commented Oct 24, 2024

With isA, I always have to end up casting to the desired type as well if I want to use members on the specified T type, as we can't rely on Dart's type promotion.

if (node.isA<HTMLAnchorElement>()) {
  final anchor = node as HTMLAnchorElement;
}

I've found myself wanting to add an extension method like:

extension on JSAny? {
  T? asA<T extends JSAny?>() {
    if (isA<T>()) {
      return this as T;
    }

    return null;
  }
}

So I can easily store the result without casting separately within the if.

if (node.asA<HTMLAnchorElement>() case final anchor?) {
  // ...
}

Yes I can add this myself, but I feel this is a pretty common case, so some version of it might be useful in dart:js_interop (if it makes sense). tryAsA could also work as a name if it's desired to distinguish from Dart's as which can throw.

@parlough parlough added web-js-interop Issues that impact all js interop area-web Use area-web for Dart web related issues, including the DDC and dart2js compilers and JS interop. labels Oct 24, 2024
@parlough parlough changed the title asA to correspond to isA [js inteorp] asA to correspond to isA Oct 24, 2024
@srujzs
Copy link
Contributor

srujzs commented Oct 25, 2024

Similar issue here: #54138

I avoided adding this because I was a little worried users might do both an isA and an asA e.g.

if (node.isA<HTMLAnchorElement>()) {
  var anchor = node.asA<HTMLAnchorElement>();
}

leading to duplicate interop type-checks. That being said, I do like the one-liner of node.asA<HTMLAnchorElement>() case final anchor?, so I'm torn. :)

Also, I actually would want this to throw if the type is wrong. Is there a reason we would not want this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-web Use area-web for Dart web related issues, including the DDC and dart2js compilers and JS interop. web-js-interop Issues that impact all js interop
Projects
Status: No status
Development

No branches or pull requests

2 participants