如何用非空断言重构代码解决TS2532 'Object is possibly undefined'错误?
问题描述
TypeScript代码如下:
export const tfModules = (moduleIds: readonly string[], mapping: Map<string, [string, string]>): string[] => moduleIds.map(m => mapping.get(m).at(0)) .filter(m => m !== undefined) .map(m => m!);
出现错误:
error TS2532: Object is possibly 'undefined'.
需求:使用非空断言表明值不可能为null或undefined的最简方法是什么?
解决方案
报错根源是mapping.get(m)可能返回undefined(当Map中无对应key时),TypeScript不允许直接对可能为undefined的值调用.at(0)。最简修复方式是在mapping.get(m)后添加非空断言!,明确告知TypeScript该值一定存在:
export const tfModules = (moduleIds: readonly string[], mapping: Map<string, [string, string]>): string[] => moduleIds.map(m => mapping.get(m)!.at(0)) .filter(m => m !== undefined) .map(m => m!);
如果能确保所有moduleIds中的元素都存在于mapping中,后续的filter和第二个map的非空断言也可省略,进一步简化代码:
export const tfModules = (moduleIds: readonly string[], mapping: Map<string, [string, string]>): string[] => moduleIds.map(m => mapping.get(m)!.at(0)!);
注意:非空断言
!是开发者向TypeScript做出的承诺,需确保对应值实际不会是null或undefined。若运行时存在Map中未收录的key,会触发运行时错误,需谨慎使用。
内容的提问来源于stack exchange,提问作者Milenko Markovic
相关产品推荐
相关产品推荐

