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

TypeScript移除对象空值触发TS2322错误的原因咨询

TypeScript移除对象空值时出现类型错误的原因

问题代码

interface ApiParams {
  foo?: string,
  bar?: string,
}
const params: ApiParams = { foo: 'foo', bar: 'bar' };
const filtered: ApiParams = {};
Object.keys(params).forEach((key: keyof ApiParams) => {
  if (params[key] != undefined) {
    filtered[key] = params[key];
  }
})

报错信息

error TS2322: Type 'string | number | boolean' is not assignable to type 'never'.
  Type 'string' is not assignable to type 'never'.

  filtered[key] = params[key];

错误原因

  • Object.keys()的类型不匹配:Object.keys()返回的是string[]类型,而非keyof ApiParams类型。强行把循环变量key标注为keyof ApiParams,会打乱TypeScript的类型推断逻辑——它无法确认当前遍历的key确实属于ApiParams定义的属性,进而无法正确判断filtered[key]的类型。
  • 类型推断冲突:当TypeScript无法确定key对应的具体属性时,会将filtered[key]的类型推断为never(因为filtered初始为空对象,且属性为可选类型),而params[key]的类型是string | undefined,两者类型不兼容,因此抛出赋值错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 11:34:54