TypeScript中matchAll匹配项index属性为可选类型的疑问
为什么matchAll返回的match.index被TypeScript标记为可选?
这不是TypeScript的bug,是你没注意到TS静态类型系统的保守设计逻辑。
MDN文档描述的是运行时的实际行为:只要matchAll返回了匹配结果,每个匹配对象的index属性必然存在,是匹配内容在原字符串中的起始位置。但TypeScript的类型定义把index标记为number | undefined,原因是TS无法在编译期百分百确定你的代码运行时一定会匹配到内容——它会做最严格的类型兜底,覆盖所有理论上可能的场景,哪怕这些场景在你的代码里不会出现。
要解决这个类型报错,有两种简单方法:
- 用非空断言符
!明确告诉TS这个index一定存在:const nums: number[] = [...'a'.matchAll(/a/g)].map(match => match.index!); - 用类型守卫做过滤(更严谨,适合不确定是否有匹配结果的场景):
const nums = [...'a'.matchAll(/a/g)] .filter((match): match is RegExpMatchArray & { index: number } => match.index !== undefined) .map(match => match.index);
内容的提问来源于stack exchange,提问作者eri412
相关产品推荐
相关产品推荐

