M
M
miliko mikoyan2019-02-07 16:11:11
typescript
miliko mikoyan, 2019-02-07 16:11:11

Property 'butlers' does not exist on type 'House'?

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

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Interface, 2019-02-07
@miliko0022

What bothers you? Your function returns the union type. So it's either one or the other. That is, the set of fields in the result is the intersection of the set of fields Mansion and House. There is no butlers field in the intersection.
If you manually cast to as Mansion as 0xD34F says, you may run into a runtime error. TS is telling you the truth.
You need to decide what your function does:
- return one of the two - then it can return a House, and there really are no butlers
- returns a House and pads its butlers to 10? Then maybe you need a new type at all.
If you want to return something that is both Mansion and House use &:

function getProperty() : ( Mansion & House) {
...

Such code reads "return an object that is both a Mansion and a House". In this case, the type will have a union of the sets of fields Mansion and House
PS if Mansion is a subspecies of House - you can use extends:
interface House {
    bedrooms: number,
    bathrooms: number
}
interface Mansion extends House {
    butlers: number
}

0
0xD34F, 2019-02-07
@0xD34F

const property = getProperty() as Mansion;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question