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?
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
I have the same issue as below. In my case, my code is
handleClick={(p: ActionFieldClickParam) =>
this.props.handleClick({ p, index })
}
then, I solved by adding '?.' and changed function call like this.props.handleClick?.({ p, index })
In your case, you should add next to the call function:
props.onBoundsChanged?.(map)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With