typescript - 回调中对象可能为 null

标签 typescript

我有以下代码:

             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/

相关文章:

typescript - 是否可以为多类型参数类/函数的多个参数创建类型别名?

typescript - 未定义的组件没有路由配置,也就是如何配置 Angular 2 路由器进行单元测试?

Typescript:根据预期的返回类型约束函数泛型类型

typescript 、声明和 CommonJS

typescript - 如何在使用 React Navigation 和 TypeScript 时使用 Jest 和 Enzyme 对静态 navigationOptions 进行单元测试?

javascript - 大于或等于(基于 bool 条件)

typescript - 使用来自另一个文件的 Typescript 类型定义

javascript - TypeScript 类和 JS 范围混淆(再次)

types - 定义 TypeScript 回调类型

node.js - 如何使 Node 行读取器有条件地跳过行