Answer the question
In order to leave comments, you need to log in
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
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) {
...
interface House {
bedrooms: number,
bathrooms: number
}
interface Mansion extends House {
butlers: number
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question