根据不同的参数推断参数类型

我想知道是否有可能在使用let d = [ [{ "product_name": "prod-1","product_url": "http:\\www.google.com" }] ] for (let i = 0; i < d.length; i++) { for (let j = 0; j < d[i].length; j++) { if(typeof d[i][j] != "undefined"){ console.log(d[i][j]["product_name"]); console.log(d[i][j]["product_url"]); } } }时基于另一个参数来推断参数。

我有一个像array.map()这样的组件,它仅映射项目,并将每个项目传递给renderItem函数。我希望下面的<List items={cards} renderItem={renderItem} />是每个renderItem = (card) => {}项目的类型(在我的情况下为cards)。

到目前为止,我有这个:

CardDomainmodel

import { Group,ListSkeleton } from 'components'
import React,{ FC,ReactElement } from 'react'

interface IList<T> {
  isLoading?: boolean
  items: T[]
  renderItem: (item: T) => ReactElement
}

/*
---
This (T) `any` must be of whatever type `items` is?
---
*/
export const List: FC<IList<any>> = ({ items,renderItem,isLoading }) => {
  if (isLoading) {
    return <ListSkeleton />
  }

  return (
    <Group spacing={2} direction="vertical">
      {items.map((item) => renderItem(item))}
    </Group>
  )
}
chu20061 回答:根据不同的参数推断参数类型

我不认为在那里可以进行自动推断,您应该做的是将renderItem函数的card参数键入CardDomainModel,而typescript会自动检查renderItem参数是否与项目类型匹配

本文链接:https://www.f2er.com/3145810.html

大家都在问