我有以下代码:
let ctx = ref.current.getContext("2d");
if(ctx){
ctx.lineWidth=1; // here is ok!
ctx.strokeStyle=props.barStroke??"darkgray";// here is ok!
ctx.fillStyle=props.barFill??"blue"; // here is ok!
props.data.map((v,i)=>{
ctx.fillRect(i*10,0,10,props.height); //here it complain about ctx is possibly null!!
ctx.strokeRect(1*10,0,10,props.height);
})
}
我已经检查了 ctx,因此 ctx.lineWidth 工作没有错误,但在回调内部,它表明该对象可能为空。如果我使用 ctx?.method 代码无论如何都可以工作,那么在回调外部检查 null 的 ctx 怎么会在回调内部变成 null 呢? Here显示问题的链接。
最佳答案
根据 this :
这正在按预期工作。类型检查器在创建回调函数时知道 ctx 为非 null,但在调用回调时它不知道 ctx 为非 null (因为 bar 是一个可变属性,可以在调用回调函数之前或之间更改)。
建议的方法是将 ctx
复制到 const local 中,然后在回调中使用它。
关于typescript - 回调中对象可能为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61135335/