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

如何用ESLint检测并移除TypeScript中冗余的非空断言?

关于移除测试中冗余非空断言的ESLint工具询问

背景与现有解决方案

我已在项目中添加了以下类型断言辅助函数,用来在测试代码中替代非空断言符号(!):

export function expectToBeDefined<T>(
  arg: T,
): asserts arg is Exclude<T, undefined> {
  expect(arg).toBeDefined();
}

当前项目中有一个无法修改的类型设计,比如:

type User = {id?: string, name: string}

之前的测试代码不得不使用非空断言来绕过TS的类型检查:

const user: User| null = await createTestUser()
const post: Post | null = await createTestPost(user?.id!)

使用上述辅助函数后,我可以消除非空断言,同时通过类型断言让TS识别到值已被确保不为undefined:

const user: User| null = await createTestUser()
expectToBeDefined(user?.id)
const post: Post | null = await createTestPost(user.id)

需求

我想了解是否存在对应的ESLint规则或插件,能够高亮并自动移除所有冗余的非空断言(即那些已经通过expectToBeDefined这类断言函数确保值非空后的!符号)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 10:50:04