The code I have is as follows:
let ctx = ref.current.getContext("2d");
if(ctx){
ctx.lineWidth=1; // this line executes without errors
ctx.strokeStyle=props.barStroke??"darkgray";// this line executes without errors
ctx.fillStyle=props.barFill??"blue"; // this line executes without errors
props.data.map((v,i)=>{
ctx.fillRect(i*10,0,10,props.height); // here it complains that ctx may be null!!
ctx.strokeRect(1*10,0,10,props.height);
})
}
While I have checked the value of ctx and found that ctx.lineWidth works fine, I encounter an error inside the callback indicating that the object could potentially be null. Interestingly, using ctx?.method
allows the code to work regardless. How is it possible for ctx, confirmed as not null outside the callback, to become null inside it?
Here is a link demonstrating the issue.