1

Why does this not error:

interface Man {
  name: string
}

interface Dog {
  breed: string
}

type manDog = Man | Dog;


let x:manDog = {name:"test", breed:"9" }

{name:"test", breed:"9" } is neither Man nor a Dog, isn't it? and manDog should be either Man or Dog, isn't it? I read about structural typing but still don't understand why it doesn't error. Can someone explain in a beginner friendly way?

  • @TobiasS. I was trying to say I don't understand how the solution in the accepted answer `type T = {A: number, B: number} | {C: number, A?: undefined, B?: undefined };` worked –  Oct 02 '22 at 23:13
  • No, a `mandog` can have every property, a `man` or a `dog` has ... But it's only guaranteed to have a certain property if both, `man` and `dog` have this property. So accessing `x.name` will give you an error – derpirscher Oct 02 '22 at 23:17
  • `manDog` is *both* a `Man` *and* a `Dog`... that is, a `Man & Dog`. And unions are inclusive, so `Man & Dog` is assignable to `Man | Dog`. See the answers to the linked questions for more information. – jcalz Oct 03 '22 at 00:24

0 Answers0