"instanceof" type narrowing section is incorrect or ambiguous #353
Description
I am following this github issue on Typescript:
The general problem in that issue is that
if (e instanceof SomeClass)
does not narrow the type of e if e is of type any (for example if it is an exception from a catch clause).
Curious to learn more about this, I look in the handbook. On the advanced types page, section "instanceof type guards", I find a fairly explicit section:
if (padder instanceof SpaceRepeatingPadder) {
padder; // type narrowed to 'SpaceRepeatingPadder'
}
The right side of the instanceof needs to be a constructor function, and TypeScript will narrow down to:
- the type of the function’s prototype property if its type is not any
- the union of types returned by that type’s construct signatures
in that order.
My interpretation of this passage is that padder
will be narrowed down to SpaceRepeatingPadder
if the prototype property of SpaceRepeatingPadder
is not any
.
However, per TypeScript issue 8677, it is also required that the type of padder not be any
. So the handbook section is wrong, unless the antecedent of "it" in (1) is meant to be the left side of instanceof, which if that is the case it is very unclear.
So, my request: Assuming @ahejlsberg 's comments in Typescript issue 8677 to be correct, you should amend this section of the handbook by doing the following:
- Specifically state that
instanceof
type guards do not narrow if the left side isany
- Rewrite (1) from the quoted section to make the antecedent of "it" explicit