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

TypeScript 自定义非空校验函数无法触发类型推断问题求解

解决方案

你可以使用TypeScript提供的自定义类型守卫功能,给isDefined函数加上类型谓词标记,告诉TS编译器当这个函数返回true时,入参一定是非空的。

修改后的isDefined函数写法如下:

// 泛型T代表入参排除null/undefined后的实际类型
const isDefined = <T>(value: T | null | undefined): value is T => {
  return value != null
}

其中value is T就是类型谓词,TS会在条件判断分支中自动根据这个标记收窄变量类型。修改后你的完整代码可以正常运行,不会触发类型报错,也不需要任何额外的断言:

const value: number | undefined = undefined
const doSomethingWithValue = (value: number) => console.log(value)
const isDefined = <T>(value: T | null | undefined): value is T => value != null

if (isDefined(value)) {
  doSomethingWithValue(value) // TS自动识别value类型为number,无报错
}

方案优势

  • 完全符合TS严格空校验规则,不需要使用类型断言、非空断言,也不需要禁用任何ESLint规则
  • 泛型实现通用度高,任意类型的变量都可以用这个函数做非空校验,都会自动触发类型收窄
  • 运行逻辑和你原本的实现完全一致,没有额外的性能损耗

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 05:45:02