not_null.
not_null.
TTCTheo's Typesafe Cult
Created by not_null. on 12/5/2022 in #questions
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?
5 replies