Skip to content

[js inteorp] asA to correspond to isA #56957

@parlough

Description

@parlough

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-web-jsIssues related to JavaScript support for Dart Web, including DDC, dart2js, and JS interop.web-js-interopIssues that impact all js interop

    Type

    No type

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions