Skip to content

Improve instanceof with structurally identical types - #10216

Merged
Anders Hejlsberg (ahejlsberg) merged 4 commits into
masterfrom
structurallyIdenticalInstanceof
Aug 9, 2016
Merged

Anders Hejlsberg (ahejlsberg) merged 4 commits into
masterfrom
structurallyIdenticalInstanceof

Conversation

@ahejlsberg

@ahejlsberg Anders Hejlsberg (ahejlsberg) commented Aug 9, 2016 •

Copy link
Copy Markdown
Member

This PR improves typing of instanceof with structurally identical types. A type S is now considered to be an instance of a type T if

  • S and T are the same type, or
  • S is a subtype of T but not structurally identical to T.

This specifically means that two distinct but structurally identical types (such as two classes) are not considered instances of each other:

class A { a: string }
class A1 extends A { }
class A2 { a: string }
class B extends A { b: string }

function foo(x: A) {
    if (x instanceof A) {
        x;  // A
    }
    else {
        x;  // never
    }
    if (x instanceof A1) {
        x;  // A1
    }
    else {
        x;  // A
    }
    if (x instanceof A2) {
        x;  // A2
    }
    else {
        x;  // A
    }
    if (x instanceof B) {
        x;  // B
    }
    else {
        x;  // A
    }
}

These changes affect similar code written using user defined type predicates.

Fixes #7271.

@DanielRosenwasser

Copy link
Copy Markdown
Member

In your example, what is the original type of x?

@ahejlsberg

Copy link
Copy Markdown
Member Author

Daniel Rosenwasser (@DanielRosenwasser) Just fixed the example.

@ahejlsberg

Copy link
Copy Markdown
Member Author

I'm going to merge this since it is a fairly minor change and fixes some real world code breaks we'd otherwise see in the nightly build because of #10194.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

3 participants