Reputation: 2049
I'm trying to add the item
type to the object that is returned from the .map function. However, I'm getting a JSX error and I tried adding item: JSX.Element
to the Item type, but that doesn't seem to work correctly. Can someone clarify this for me? Below is the error, types, and code.
Error:
src/ListPicker.tsx:69:28 - error TS2345: Argument of type '(item: Item) => JSX.Element' is not assignable to parameter of type '(value: string, index: number, array: string[]) => Element'.
Types of parameters 'item' and 'value' are incompatible.
Type 'string' is not assignable to type 'Item'.
{props.items.map((item: Item) => {
~~~~~~~~~~~~~~~~~
Types:
// TypeScript: Types
interface Props {
title: string,
items: Array<string>,
onPress: Function,
onValueChange: Function,
}
interface Item {
label: string,
value: string,
key: number | string,
color: string,
};
ListPicker.tsx:
// Render iOS Picker
const renderIOSPicker = () => {
try {
return (
<Picker
selectedValue={value}
onValueChange={selectValue}>
{props.items.map((item: Item) => {
return (
<Picker.Item
label={item.label}
value={item.value}
key={item.key || item.label}
color={item.color}
/>
);
})}
</Picker>
)
}
catch (error) {
console.log(error);
}
};
Upvotes: 3
Views: 4086
Reputation: 202864
Looks like your props define items
to be an array of strings, so when mapping over an array of strings the map callback signature is (element: string, index: number, array: string[])
. I think if you update props interface for items
to be items: Array<Item>,
, it should now match up.
// TypeScript: Types
interface Item {
label: string,
value: string,
key: number | string,
color: string,
};
interface Props {
title: string,
items: Array<Item>, // use array of type you defined above
onPress: Function,
onValueChange: Function,
}
Upvotes: 3
Reputation: 30370
It seems the issue here is inconsistentcy between the type of item
(ie in the argument of your map function), and the type the items
array as defined in the Props
interface.
Your Props
interface defines the items
field as an array of strings, where as your rendering code expects the items
field to be an array of Item
objects.
If you are able to revise and refactor your code so the Props
is defined as:
interface Props {
title: string,
items: Array<Item>,
onPress: Function,
onValueChange: Function,
}
Then this should resolve the error.
Upvotes: 1