0

At present I am unable to access any of the properties from the "Eagle" class. I have imported my "AnyBird" type but when I try and use properties off of specifically "Eagle" it isn't recognized at all. It only sees the properties from "Bird".

I'd say "Just import Eagle as the type" but I need to have other more specialized types accepted as well. Like "Doves", "Pidgeons", "Chickens" for example. It needs to be extendable so I wanted to concatenate all of the types under "AnyBird".

Help would be super appreciated!

export type AnyBird = Bird | Eagle ;

export interface Eagle extends Bird {
    energyGain: number;
    heatGain: number;
    energyCost: number;
    heatCost: number;
}


export interface Bird {
    id: number; 
    job: number;
    jobSpecificId: number;
    level: number;
}

An example would be in a separate file I'd be like:

import { AnyBird } from './common/skills/SpecialBirdsFile';

interface Props {
    someBird: AnyBird;
}


export default class BirdThing extends Component<Props, State> {
    state = {}
    render() { 
        let {someBird} = this.props;
        <div>
            {allBirds.id} <-- WORKS!!!!!!
            {allBirds.energyGain} <---- FAILS! Cannot be found.
        </div>
    }
}
1

1 Answer 1

1

Because you're using a union type, where one of the types is a superset of the other, one way to solve this is by checking which type it is when you use the object.

For example, you can write a function called isEagle implemented something like this:

function isEagle(obj: any): obj is Eagle {
   // however you'd check if this is an "Eagle" object. Ex:
   return obj.hasOwnProperty('energyGain')
}

To use the properties on Eagle, you'd call your function like this:

const myBird: AnyBird = { ... };

if (isEagle(myBird)) {
   // properties of Eagle are available here
} else {
   // Just a base Bird object.
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.