首页 > 解决方案 > 你使用什么类型来允许 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)

标签: typescript

解决方案


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)[]>

推荐阅读