如何通过自定义函数让TypeScript确认对象已定义?
如何让TypeScript认可自定义的非空校验函数?
场景说明
使用自定义工具函数ObjectHelper.isNullOrUndefined对变量做非空判断后,TypeScript仍提示Object is possibly 'undefined'错误。希望不用写冗余的显式非空判断,让TypeScript自动识别该工具函数的校验作用。
相关代码
scaleString getter 实现
public get scaleString(): string { const previewScale = !ObjectHelper.isNullOrUndefined(this.previewWidth) && !ObjectHelper.isNullOrUndefined(this.realWidth) // 此处提示:Object is possibly 'undefined' ? this.previewWidth / this.realWidth : 1; const scaleInPercent = previewScale * this.scale * 100; return `${scaleInPercent.toFixed(2)}%`; }
ObjectHelper.isNullOrUndefined 原定义
public static isNullOrUndefined(v: object | string | boolean | number | null | undefined): boolean { return v === undefined || v === null; }
当前错误提示
- Visual Studio Code中TypeScript报错:
Object is possibly 'undefined'
现有繁琐解决方式
直接对每个变量做显式非空判断:
const previewScale = this.previewWidth !== undefined && this.previewWidth !== null && this.realWidth !== undefined && this.realWidth !== null ? this.previewWidth / this.realWidth : 1;
解决方法:用类型谓词改造工具函数
修改ObjectHelper.isNullOrUndefined的返回类型为类型谓词,让TypeScript识别该函数的类型守卫作用:
public static isNullOrUndefined(v: object | string | boolean | number | null | undefined): v is null | undefined { return v === undefined || v === null; }
改造后,当代码中出现!ObjectHelper.isNullOrUndefined(this.previewWidth)时,TypeScript会自动推断this.previewWidth不为null或undefined,不再抛出上述错误。
原理
类型谓词是TypeScript的语法特性,用于在函数中明确参数的类型判断逻辑。这里的v is null | undefined告诉编译器:
- 若函数返回
true,则参数v必然是null或undefined - 若函数返回
false,则参数v属于原类型中排除null和undefined的子集
内容的提问来源于stack exchange,提问作者broadband
相关产品推荐
相关产品推荐

