I'm trying to add types to the Item
object that is returned from unitedStates.map((item: Item) => {}
, but I can't seem to correctly add the types.
I've defined the unitedStates
array of objects as unitedStates: Array<UnitedStates>
and that seems to be correct, but I'm not sure why Item
is not correctly typed.
Error:
src/StatePicker.tsx:198:35 - error TS2345: Argument of type '(item: Item) => JSX.Element' is not assignable to parameter of type '(value: UnitedStates, index: number, array: UnitedStates[]) => Element'.
Types of parameters 'item' and 'value' are incompatible.
Type 'UnitedStates' is not assignable to type 'Item'.
{unitedStates.map((item: Item) => {
Types.tsx:
// TypeScript: Types
interface Props {
title: string,
onPress: Function,
onValueChange: Function,
}
interface Item {
label: string,
value: string,
key: number | string,
color: string,
};
interface UnitedStates {
label: string,
value: string,
};
United States (Array of Objects):
// United States
const unitedStates: Array<UnitedStates> = [
{ label: 'AL', value: 'AL' },
{ label: 'AK', value: 'AK' },
{ label: 'AZ', value: 'AZ' },
{ label: 'AR', value: 'AR' },
{ label: 'CA', value: 'CA' },
{ label: 'CO', value: 'CO' },
{ label: 'CT', value: 'CT' },
{ label: 'DE', value: 'DE' },
{ label: 'FL', value: 'FL' },
{ label: 'GA', value: 'GA' },
{ label: 'HI', value: 'HI' },
{ label: 'ID', value: 'ID' },
{ label: 'IL', value: 'IL' },
{ label: 'IN', value: 'IN' },
{ label: 'IN', value: 'IN' },
{ label: 'KS', value: 'KS' },
{ label: 'KY', value: 'KY' },
{ label: 'LA', value: 'LA' },
{ label: 'ME', value: 'ME' },
{ label: 'MD', value: 'MD' },
{ label: 'MA', value: 'MA' },
{ label: 'MI', value: 'MI' },
{ label: 'MN', value: 'MN' },
{ label: 'MS', value: 'MS' },
{ label: 'MO', value: 'MO' },
{ label: 'MT', value: 'MT' },
{ label: 'NE', value: 'NE' },
{ label: 'NV', value: 'NV' },
{ label: 'NH', value: 'NH' },
{ label: 'NJ', value: 'NJ' },
{ label: 'NM', value: 'NM' },
{ label: 'NY', value: 'NY' },
{ label: 'NC', value: 'NC' },
{ label: 'ND', value: 'ND' },
{ label: 'OH', value: 'OH' },
{ label: 'OK', value: 'OK' },
{ label: 'OR', value: 'OR' },
{ label: 'PA', value: 'PA' },
{ label: 'RI', value: 'RI' },
{ label: 'SC', value: 'SC' },
{ label: 'SD', value: 'SD' },
{ label: 'TN', value: 'TN' },
{ label: 'TX', value: 'TX' },
{ label: 'UT', value: 'UT' },
{ label: 'VT', value: 'VT' },
{ label: 'VA', value: 'VA' },
{ label: 'WA', value: 'WA' },
{ label: 'WV', value: 'WV' },
{ label: 'WI', value: 'WI' },
{ label: 'WY', value: 'WY' },
];
Render Method:
// Render iOS Picker
const renderIOSPicker = () => {
try {
return (
<Picker
selectedValue={state}
onValueChange={selectState}>
{unitedStates.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);
}
};