【问题标题】:JSX Element Type Error: Adding Types to object returned from .map functionJSX 元素类型错误:将类型添加到从 .map 函数返回的对象
【发布时间】:2020-04-29 15:34:39
【问题描述】:

我正在尝试将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);
    }
  };

【问题讨论】:

  • 看起来你的道具将items定义为一个字符串数组,所以当映射一个字符串数组时,映射回调签名是(element: string, index: number, array: string[])。我认为如果您将items 的道具接口更新为items: Array&lt;Item&gt;,,它现在应该匹配。如果这是正确的,那么我可以添加为答案。

标签: reactjs typescript react-native types typescript-typings


【解决方案1】:

看起来您的道具将items 定义为字符串数组,因此当映射字符串数组时,映射回调签名为(element: string, index: number, array: string[])。我想如果你将 items 的 props 接口更新为 items: Array&lt;Item&gt;,,它现在应该匹配了。

// 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,
}

【讨论】:

    【解决方案2】:

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2020-04-30
      • 2019-07-21
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 2020-05-31
      • 2019-12-12
      • 1970-01-01
      相关资源
      最近更新 更多