Skip to content

Feature Request / Proposal: constructor type guard #23274

Closed

Description

@sheley1998

In most cases, constructor comparison is faster than instanceof and typeof, thus using it as type guard can improve performance. The code below demonstrates the desired behavior:

const el:HTMLElement = document.createElement('canvas');

if (el.constructor === HTMLCanvasElement) {
    //inside of this scope, el is parsed as an instance of HTMLCanvasElement
    el.getContext('2d');
}

Activity

  1. changed the title [-]Feature Request / Proposal: constructor ty[/-] on Apr 9, 2018
  2. added
    Suggestion
    In Discussion
    on Apr 9, 2018
  3. mhegazy commented on Apr 10, 2018

    @mhegazy
    Contributor

    related to #3841

  4. added
    Effort: Moderate
    and removed
    In Discussion
    on Apr 17, 2018
  5. RyanCavanaugh commented on Apr 17, 2018

    @RyanCavanaugh
    Member

    Accepting PRs for a new kind of type guard (IOW one that specifically looks for this syntactic pattern). Note that the false arm here can't perform any narrowing of a union due to constructor checks not identifying subclasses.

  6. Kingwl commented on Apr 22, 2018

    @Kingwl
    Contributor

    i’d like to work on this 😄

  7. austincummings commented on Jul 2, 2019

    @austincummings
    Contributor

    Is this issue being worked? If not I'd like to try and add this.

  8. bruce-forte commented on May 21, 2020

    @bruce-forte

    Hey. Why was this closed? :(

  9. Kingwl commented on May 21, 2020

    @Kingwl
    Contributor

    Because #32774 is merged.

  10. ikonst commented on Jun 24, 2024

    @ikonst

    The snippet in the issue doesn't work. Nathan Shively-Sanders (@sandersn), can we reopen?

    The only thing that works with #32774 is

    const el: HTMLDivElement | HTMLCanvasElement = document.createElement(tagName);
    if (el.constructor === HTMLCanvasElement) {
      //inside of this scope, el is parsed as an instance of HTMLCanvasElement
      el.getContext('2d');
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Effort: ModerateSuggestion

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions