TypeScript非空断言运算符失效问题及合法解决方案咨询
TypeScript可选属性非空断言报错问题
先定义包含可选属性的类型:
type tp1 = {a: string, b?: Array<number>};
接着创建包含该可选属性的对象:
const a: tp1 = {a: '10', b: [1,2,3]};
测试非空断言时,第一个日志正常输出,但第二个日志抛出Object is possibly 'undefined'错误:
console.log('1st test log ', a!.b); // 正常运行 console.log('2nd test log ', a!.b[2]); // 报错:Object is possibly 'undefined'
报错原因
a!.b中的非空断言仅作用于对象a本身,只是告诉TypeScripta一定不为null或undefined,但并没有对可选属性b做断言。在类型定义里,b依然是Array<number> | undefined的联合类型,所以直接访问a!.b[2]时,TypeScript仍会检查b是否可能为undefined。
消除报错的方法
- 给
b添加非空断言:将断言精准作用到b上,明确告知TypeScriptb一定存在console.log('2nd test log ', a.b![2]); // 或者 console.log('2nd test log ', (a!.b)![2]); - 使用类型守卫:通过条件判断缩小
b的类型范围if (a.b) { console.log('2nd test log ', a.b[2]); } - 类型断言:直接将
a.b断言为数组类型console.log('2nd test log ', (a.b as Array<number>)[2]); - 修改类型定义(若
b实际必存在):如果业务场景中b并非真正可选,直接移除类型里的?type tp1 = {a: string, b: Array<number>};
内容的提问来源于stack exchange,提问作者AshBadCoder
相关产品推荐
相关产品推荐

