Skip to content
This repository was archived by the owner on Oct 12, 2022. It is now read-only.
This repository was archived by the owner on Oct 12, 2022. It is now read-only.

"instanceof" type narrowing section is incorrect or ambiguous #353

Open
@mcclure

Description

@mcclure

I am following this github issue on Typescript:

microsoft/TypeScript#8677

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:

  1. the type of the function’s prototype property if its type is not any
  2. 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:

  1. Specifically state that instanceof type guards do not narrow if the left side is any
  2. Rewrite (1) from the quoted section to make the antecedent of "it" explicit

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions