2

I', having a Problem with the TypeScript compiler. Why aren't any errors shown for the following code snippet?

class A {

}

class B {
  myVar:string;
}

class Foo {
  bar(a:A){}

  doSomething(){
    this.bar(new B());
  }
}

Since B is no A, shouldn't the bar-call with a B be prohibited?

1 Answer 1

5

The *bar-*call shouldn't be prohibited here, because TypeScript has structural type relationships. So, A and B are compared not just by names, but rather by enumerating and comparing their members, according to the specification. As follows.

  1. bar() call requires its argument type to be assignable to the corresponding parameter type. So, "new B()" type should be assignable to "A" (specification section 4.12.1 "Overload resolution")

  2. If we compare "B" and "A" structurally according to the algorithm presented in specification section 3.8.4 "Assignment compatibility", we see that "B" is assignable to "A".

If you want to experiment further, just add some property "x" to the class A. And you'll see your error.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, didn't know that the comparison was based on the structur. So it's rather a feature than a bug ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.