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

prop-types的arrayOf(string)定义与TypeScript类型不兼容问题

报错根本原因

prop-types 库中 PTs.string 校验默认允许数组元素为 null 或 undefined,但你 TypeScript 接口中定义的 list 是元素仅为 string 类型的数组,两者类型不匹配触发报错。

解决方案

方案1:调整PropTypes校验规则(最推荐)

给数组元素的校验加上 .isRequired,约束数组元素不能为 null/undefined,和TS类型保持一致:

App.propTypes = {
  list: PTs.arrayOf(PTs.string.isRequired)
};

方案2:调整TS接口定义

如果你的业务确实允许数组内存在 null/undefined 元素,修改接口定义适配PropTypes的规则:

interface AppProps {
  list?: (string | null | undefined)[];
}

方案3:类型断言(仅临时兼容用,不推荐)

如果不想修改原有逻辑,可通过类型断言绕过TS校验:

App.propTypes = {
  list: PTs.arrayOf(PTs.string) as PTs.Validator<string[] | undefined>
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 18:27:03