typescript props as object or array

Hey guys, I have a select that can or not be a multi-select So my select props are
type SelectProps = {
items: SelectItem[]
selectedItem: SelectItem | SelectItem[]
setSelectedItem: (arg: SelectItem | SelectItem[]) => void
multiple?: boolean
}
type SelectProps = {
items: SelectItem[]
selectedItem: SelectItem | SelectItem[]
setSelectedItem: (arg: SelectItem | SelectItem[]) => void
multiple?: boolean
}
so I can take a SelectItem or an array of those my problem is in the `setSelectedItem when I call my component
<Select
key={idx}
items={filter.options}
selectedItem={filter.selectedItems}
setSelectedItem={filter.setSelectedItems}
/>
<Select
key={idx}
items={filter.options}
selectedItem={filter.selectedItems}
setSelectedItem={filter.setSelectedItems}
/>
I got the error
Type '(arg: SelectItem[]) => void' is not assignable to type '(arg: SelectItem | SelectItem[]) => void'.
Types of parameters 'arg' and 'arg' are incompatible.
Type 'SelectItem | SelectItem[]' is not assignable to type 'SelectItem[]'.
Type 'SelectItem' is missing the following properties from type 'SelectItem[]': length, pop, push, concat, and 29 more.ts(2322)
Select.tsx(13, 3): The expected type comes from property 'setSelectedItem' which is declared here on type 'IntrinsicAttributes & SelectProps'
Type '(arg: SelectItem[]) => void' is not assignable to type '(arg: SelectItem | SelectItem[]) => void'.
Types of parameters 'arg' and 'arg' are incompatible.
Type 'SelectItem | SelectItem[]' is not assignable to type 'SelectItem[]'.
Type 'SelectItem' is missing the following properties from type 'SelectItem[]': length, pop, push, concat, and 29 more.ts(2322)
Select.tsx(13, 3): The expected type comes from property 'setSelectedItem' which is declared here on type 'IntrinsicAttributes & SelectProps'
I understand that the problem is something to do with it either being an object or an array and so it has different properties How can I make it typesafe and satisfy both cases?
3 Replies
not_null.
not_null.OP3y ago
my filter in this case is of type
export type FilterType = {
selectedItems: SelectItem[]
setSelectedItems: (arg: SelectItem[]) => void
options: SelectItem[]
}
export type FilterType = {
selectedItems: SelectItem[]
setSelectedItems: (arg: SelectItem[]) => void
options: SelectItem[]
}
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
not_null.
not_null.OP3y ago
oh I didnt thought of that, then I can only pass the multiple on the one that has an array I mean, it doesnt even need to be a prop at this point I guess, whenever its an array of selected it will be multiple
Want results from more Discord servers?
Add your server