Home > database >  Unable to access object properties with dot notation in typescript
Unable to access object properties with dot notation in typescript

Time:05-24

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?

CodePudding user response:

You have to dependent playerSystem into useEffect

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

CodePudding user response:

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;
}
  • Related