The explanation for why typescript doesn't display errors when you write const instance : A = new B()
is due to its use of structural typing. Essentially, if the structure or shape aligns with each other, typescript accepts it without any issues.
For instance, consider the following scenario:
class A {
foo() : boolean { return true }
}
class B {
foo() : boolean { return true }
}
const bar : A = new B()
The typescript compiler views the above code as equivalent because of their similar structures. However, if there's a change in structure, the compiler will identify and flag it.
class AA {
foo() : boolean { return true }
}
class BB {
foo() : string { return "true" }
}
const foobar : AA = new BB()
In such cases, tsc will generate an error message like this:
Type 'BB' is not assignable to type 'AA'. The types returned by 'foo()' are incompatible between these types. Type 'string' is not assignable to type 'boolean'
In your example, B
mirrors the exact structure of A
since public var1: string
exists in both classes. Thus, B
can be assigned to A
. On the contrary,
const instance: B = new A()
the compiler will raise an issue because A
doesn't entirely match the structure of
B</code, given that <code>public var2: string
is in
B
but not in
A
.
In contrast, C++, Java, and certain other languages employing nominal typing would catch such discrepancies during compilation.