Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove TS2722: Cannot invoke an object which is possibly 'undefined'. error?

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?

like image 677
forJ Avatar asked Dec 31 '22 07:12

forJ


2 Answers

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

like image 82
16oh4 Avatar answered Feb 06 '23 23:02

16oh4


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)
like image 22
Günay Gültekin Avatar answered Feb 06 '23 22:02

Günay Gültekin