3

Given:

class Base {}
class D1 extends Base{}
class D2 extends Base{}

const d1: D1 = new D1();

function printD2(d2: D2) {
    console.log(d2)
}
printD2(d1);

I would have expected an error passing d1 into printD2. They are structurally the same, yet they are derived types. Why is this? How to prevent this? At runtime this d1 instanceof D2 would return false.

https://www.typescriptlang.org/play?ts=4.6.4#code/MYGwhgzhAEBCkFNoG8C+AoUkYBECM0CAHgC4IB2AJjPBAmpuFNDgEyGkXVyIOYD25CCWiU8ALhYEAvNHIIA7lIAUASgDc6dADMAruWAkAloOgAHAE5HyJNssqtJbVSnTR30YIIj8QCAHQg-ADm9qyq6BiW1ras9ngaQA

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • 1
    That is the correct expected behavior: Typescript is structurally typed not nominally typed. You can get around this by giving the derived classes some unique property to make them structurally different. – Jared Smith May 05 '23 at 20:17
  • 1
    TypeScript uses structural typing. Whenever two types are structurally the name, they are considered “compatible”. – Jean-Philippe Pellet May 05 '23 at 20:18

0 Answers0