interface House { bedrooms: number, bathrooms: number } interface Mansion { bedrooms: number, bathrooms : number, butlers: number } function getProperty() : ( Mansion | House) { return { bedrooms: 10, bathrooms: 10, butlers: 10 } // ... } const property = getProperty(); const bedroomCount = property.butlers; //error 
  • Try to check what this code compiled into. - Dmitry Miroshnichenko
  • Type error: Property 'butlers' does not exist on type' House | Mansion '. Property 'butlers' does not exist on type 'House'. TS2339 29 | const property = getProperty (); 30 | > 31 | const bedroomCount = property.butlers; - Silicum Silium pm
  • Try to put butlers?: number in the interface. - Dmitry Miroshnichenko
  • the same result - Silicum Silium
  • joxi.ru/DrlVLlLuV0geV2 - So it will not fight. If several interfaces are implemented for 1 function, then in all interfaces the fields to which we access should be described after executing the function. - Dmitry Miroshnichenko

1 answer 1

If several interfaces are implemented for 1 function, then in all interfaces the fields to which we access should be described after executing the function.

 interface House { bedrooms: number, bathrooms: number, butlers?: undefined } interface Mansion { bedrooms: number, bathrooms: number, butlers: number } function getProperty(): (Mansion | House) { return { bedrooms: 10, bathrooms: 10, butlers: 10 } } const property = getProperty(); const bedroomCount = property.butlers;