首页 > 解决方案 > JSX 元素类型错误:将类型添加到从 .map 函数返回的对象

问题描述

我正在尝试将item 类型添加到从 .map 函数返回的对象中。但是,我收到 JSX 错误,我尝试添加item: JSX.Element到 Item 类型,但这似乎无法正常工作。有人可以为我澄清一下吗?下面是错误、类型和代码。

错误:

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) => {
                              ~~~~~~~~~~~~~~~~~

类型:

// 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);
    }
  };

标签: reactjstypescriptreact-nativetypestypescript-typings

解决方案


似乎这里的问题是item(即在您的 map 函数的参数中)的类型与接口items中定义的数组类型之间的不一致。Props

您的Props界面将items字段定义为字符串数组,而您的渲染代码期望该字段是对象items数组。Item

如果您能够修改和重构您的代码,那么Props定义为:

interface Props {
  title: string,
  items: Array<Item>,
  onPress: Function,
  onValueChange: Function,
}

那么这应该可以解决错误。


推荐阅读