简体   繁体   中英

Unable to access object properties with dot notation in typescript

I have an object that is being passed a prop playerSystem from one component to the other. This is playerSystem logged to the console.

sector: {
{
cords: "A-6450"
systemName: "A-79672"
systemPlanets: (8) ['Ocean', 'Rocky', 'Gas', 'Temperate', 'Gas', 'Frozen', 'Lava', 'Frozen']
systemStar: "Red-Dwarf"
}
}

This is being logged to the console so I know there is not a problem with the data. I want to access the inner object of sector with the properties like systemName , so I am trying to do that

 useEffect(() => {
        console.log(playerSystem.systemName)
        console.log(playerSystem.sector)
    }, [])

Both of these throw the same error, Property 'systemName'/'sector' does not exist on type 'Object'.
How can I access the nested properties of my object?

You have to dependent playerSystem into useEffect

 useEffect(() => {
        console.log(playerSystem.systemName)
        console.log(playerSystem.sector)
    }, [playerSystem])

Try representing the type of playerSystem prop that a component is receiving, only then ts will be able to know the properties that exist on that object.

type sectorType = {
 systemStar: string,
 systemPlanets: string[],
 systemName: string,
 cords: string
};
interface playerSystemProps {
  playerSystem: sectorType;
  setPlayerSystem: Function;
}

In case anyone sees this in the future. My issue was that my object was actually an array. It was [{data.subdata}] So i was unable to use dot notation unless I did data[0].subdata

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM