Issue
I have a function looking like this
let bcInst;
if(props.onBoundsChanged){
bcInst = kakao.maps.event.addListener(map, 'bounds_changed',()=>{
props.onBoundsChanged(map); //I get error here
})
}
props interface looking like below
interface IMapProps{
mapId?: string;
longitude: number;
latitude: number;
level:number;
onBoundsChanged?:{
(map:any) : void
}
}
Even if I am checking for props.onBoundsChanged in an if statement, I am getting TS2722: Cannot invoke an object which is possibly 'undefined'. error at the position I am using props.onBoundsChanged. How do I solve this issue?
Solution
TypeScript is saying your onBoundsChanged
might be undefined because you have defined it as an optional (?)
property in the interface IMapProps:
onBoundsChanged?: {}
Your check for onBoundsChanged
for a truthy
value is correct, but the event listener will be invoked at a later time, which means onBoundsChanged
might be undefined like @basarat specified. You can avoid this error by using one of these inside your listener.
Check for truthy value before calling onBoundsChanged
if(props.onBoundsChanged) onBoundsChanged(map)
Use optional chaining ?.
operator to access onBoundsChanged
props?.onBoundsChanged(map)
Some useful learning resources:
You can read more about truthy
values from the MDN here.
https://developer.mozilla.org/en-US/docs/Glossary/Truthy
More about the optional chaining ?.
operator here.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
Answered By - 16oh4
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.