Skip to content

Conversation

ahejlsberg
Copy link
Member

@ahejlsberg ahejlsberg commented Aug 9, 2016

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
Member

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

@ahejlsberg
Copy link
Member Author

@DanielRosenwasser Just fixed the example.

@ahejlsberg
Copy link
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
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants