typescript - 你使用什么类型来允许 React.SetStateAction 中的 null 或数据?
问题描述
我需要在数组末尾添加一个“null”,因为这是第 3 部分库所期望的,以表明有更多数据要获取。如果没有启用“StrictNullCheck”,一切正常。我的类型应该在这里?
数据是
const data: {
_id: string;
name: string;
}[]
代码:
const [companies, setCompanies] = React.useState<ItemListData[] | null>([])
setCompanies([...data, null] // Adding a null here is causing the type error
错误:
Argument of type '({ _id: string; name: string; } | null)[]' is not assignable to parameter of type 'SetStateAction<ItemListData[] | null>'.
Type '({ _id: string; name: string; } | null)[]' is not assignable to type 'ItemListData[]'.
Type '{ _id: string; name: string; } | null' is not assignable to type 'ItemListData'.
Type 'null' is not assignable to type 'ItemListData'.ts(2345)
解决方案
I suspect that this:
React.useState<ItemListData[] | null>
means "the type can be an array of ItemListData
or the type can be null
". Which means you either have an array or you have null
, but the array itself must contain ItemListData
.
What you want is "the type can be an array of either ItemListData
or null
". Which would mean that the type itself must always be an array, but that array can contain either ItemListData
or null
.
Perhaps something like this:
React.useState<(ItemListData | null)[]>
推荐阅读
- kubernetes - k8s - 删除集群时持久存储会发生什么/?
- java - 启用持久性的嵌入式 Ignite 实例重启速度非常慢
- angular - Rxjs:[ts] 类型“UnaryFunction”上不存在属性“管道”
, 可观察的 >'。任何 - openssl - 使用 Diffie-Hellman 参数(“p”和“g”)生成私钥和公钥。结果是“Pub_key”和“Priv_key”(1024 位/128 字节)
- python - Pandas 中的 Shift 分组系列
- bash - 在 shell 集中使用 shell 变量
- python - Pandas:CSV 标题和数据行大小不匹配
- python - 如何在 Jupyter Notebook 的 API 有效负载中使用变量
- selenium - 无法将测试执行结果传递给 Robo 框架中的变量
- angular - 当我从 web 服务填充数据时,Angular6 和 ng2-charts 不显示任何图表