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

TypeScript过滤字符串数组报ts(2345)错,如何修改代码?

问题解决:TypeScript useState更新函数类型错误

错误原因

代码存在两个关键问题引发TS报错:

  1. useState<string[] | []>的类型定义冗余,[]本身就是string[]的子类型,这种联合类型会让TypeScript错误推断setAddMore的参数类型,认为它只能接受string[],而非函数式更新。
  2. 参数value: String使用了大写构造函数类型,应改为小写的基本类型string。

修改后的代码

const [addMore, setAddMore] = useState<string[]>(["1"]);

const removeAdd = (value: string) => {
  setAddMore((prev: string[]) => {
    return prev.filter((valueAt: string) => valueAt !== value);
  });
};

关键修改点

  • 移除useState类型中的| [],直接使用string[],TS会自动处理空数组或非空数组场景。
  • 将value: String改为value: string,遵循TypeScript基本类型使用规范。
  • 删除不必要的as string[]类型断言,filter返回的数组类型本身就是string[],无需额外断言。

内容的提问来源于stack exchange,提问作者Captai-N

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 04:09:52