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

TS报错:(string | number)[]无法赋值给number[]类型问题求解

错误根因

filter回调上标注的(el): boolean返回类型,会让TypeScript将该回调识别为普通布尔判断函数,不会触发过滤后的数组类型收窄逻辑。此时filter返回值类型和原数组保持一致,为(string | number)[],无法赋值给number[]类型的resArray,因此抛出TS2322类型不匹配错误。

TypeScript 对Array.filter做了特殊类型支持:仅当传入的回调是类型守卫(返回值为类型谓词格式)时,TS才会根据守卫逻辑收窄过滤后的数组类型。

修复方案

将回调的返回类型从普通boolean修改为类型谓词el is number,显式告知TS过滤后剩余元素均为number类型即可,修正后代码如下:

function numArray(array:  (string | number)[]): number[] {
  const resArray: number[] = array.filter((el): el is number => typeof el === 'number');
  return resArray;
}

部分高版本TS可通过typeof判断自动推导filter的类型守卫,无需手动标注类型谓词,但显式编写el is number是跨版本兼容性最好的写法,不会因TS版本迭代出现推导失效问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 13:09:26