'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?
Solution 1:[1]
You have to dependent playerSystem into useEffect
useEffect(() => {
console.log(playerSystem.systemName)
console.log(playerSystem.sector)
}, [playerSystem])
Solution 2:[2]
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mikenlanggio |
| Solution 2 | Harshita |
