You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否用全局函数做空值校验并通过TypeScript ESLint检查?

问题:使用全局校验函数做空值校验时无法通过ESLint检查?

在TypeScript项目中定义了如下全局校验函数:

const isNotNullNumber = (e: number | undefined) => {
  if (e !== null && e !== undefined && e !== 0) {
    return true;
  }
  return false;
};

// 通过ESLint检查
if (promotionBadgeData?.discountPercent) {
  icon1 = <Text>{`${promotionBadgeData?.discountPercent}%\nOff`}</Text>;
}

// 通过ESLint检查
if (
  promotionBadgeData?.discountPercent !== null &&
  promotionBadgeData?.discountPercent !== undefined &&
  promotionBadgeData?.discountPercent !== 0
) {
  icon1 = <Text>{`${promotionBadgeData?.discountPercent}%\nOff`}</Text>;
}

// 未通过ESLint检查
if (isNotNullNumber(promotionBadgeData?.discountPercent)) {
  icon1 = <Text>{`${promotionBadgeData?.discountPercent}%\nOff`}</Text>;
}

直接编写条件判断可通过ESLint,但调用该全局函数校验时触发错误:ESLint: Invalid type "number | undefined" of template literal expression.(@typescript-eslint/restrict-template-expressions),请问是否可使用全局函数做空值校验并通过ESLint检查?


解决方案

可以用全局函数完成校验并通过ESLint,核心是把普通校验函数改成类型守卫函数,让TypeScript和ESLint能识别函数调用后的类型收窄效果。

修改全局函数为类型守卫

把函数的返回类型声明为e is number,这样TypeScript会明确:当函数返回true时,参数e的类型已经从number | undefined收窄为number。

// 修改后的类型守卫函数
const isNotNullNumber = (e: number | undefined): e is number => {
  return e !== null && e !== undefined && e !== 0;
};

使用修改后的函数校验

此时再调用函数做判断,ESLint和TypeScript都能识别出promotionBadgeData?.discountPercent在条件成立时是number类型,不会再触发模板表达式的类型错误:

// 现在可以通过ESLint检查
if (isNotNullNumber(promotionBadgeData?.discountPercent)) {
  icon1 = <Text>{`${promotionBadgeData?.discountPercent}%\nOff`}</Text>;
}

全局函数的类型识别注意事项

如果这个函数是全局可用的,要确保它的类型定义能被项目所有文件识别:

  • 可以把函数定义放在全局类型声明文件(比如global.d.ts)中
  • 或者通过export导出后在需要的地方导入(模块环境下)

内容的提问来源于stack exchange,提问作者Ryan Yu Ryan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 11:46:08