Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

typescript - What type do you use to allow null or data in a React.SetStateAction?

I need to add a 'null' at the end of array, as that is what is expected by a 3rd part library to signal that there is more data to fetch. Without 'StrictNullCheck' enabled everything is working fine. What should my type be here?

data is

const data: {
    _id: string;
    name: string;
}[]

Code:

const [companies, setCompanies] = React.useState<ItemListData[] | null>([])
setCompanies([...data, null] // Adding a null here is causing the type error

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)
question from:https://stackoverflow.com/questions/65902328/what-type-do-you-use-to-allow-null-or-data-in-a-react-setstateaction

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...