Typescript: Feature Request / Proposal: constructor type guard

Created on 9 Apr 2018  ·  6Comments  ·  Source: microsoft/TypeScript

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');
}
Moderate Suggestion help wanted

Most helpful comment

i’d like to work on this :smile:

All 6 comments

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.

i’d like to work on this :smile:

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

Hey. Why was this closed? :(

Because #32774 is merged.

Was this page helpful?
0 / 5 - 0 ratings