1

I would expect the following code to fail to transpile, as B should not be a valid type for array.push. What am I missing?

class A {};
class B {};
const arr: A[] = [];
arr.push(new B());
Guillaume CR
  • 3,006
  • 1
  • 19
  • 31
  • 5
    `A` and `B` are structurally the same, that's why TypeScript accepts it: https://www.typescriptlang.org/docs/handbook/type-compatibility.html – UnholySheep Aug 29 '18 at 17:07
  • 1
    Here's a helpful answer on S.O. https://stackoverflow.com/a/39562956/831878 – Ray Toal Aug 29 '18 at 17:08
  • also related: https://stackoverflow.com/questions/49135069/typescript-generic-type-check-not-working-as-expected – artem Aug 30 '18 at 01:32

1 Answers1

6

TypeScript uses structural compatibility to determine type compatibility. The classes are structurally compatible since they have the same properties (empty object).

See: https://www.typescriptlang.org/docs/handbook/type-compatibility.html

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405