首页 > 解决方案 > 对象在回调中可能为 null

问题描述

我有以下代码:

             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 呢? 这里有一个显示问题的链接。

标签: typescript

解决方案


按照这个

这是按预期工作的。类型检查器ctx在创建回调函数时知道它是非空的,但在调用回调时它不知道它ctx是非空的(因为 bar 是一个可变属性,可以在调用之前或调用之间更改回调函数)。

建议的方法是复制ctx到 const local 然后在回调中使用它。


推荐阅读