简体   繁体   English

如何修复接口和类型?

[英]How to fix Interface and type?

I try to write component, that should get data with diferent variable names from api and render ut.我尝试编写组件,它应该从 api 获取具有不同变量名的数据并渲染 ut。 I have two response with same data but with diferent variable names for example:我有两个具有相同数据但具有不同变量名称的响应,例如:

FirstReq {
    id          number
    published   boolean
    publishDate string
    newsImage   string
    newsTitle   string
}

SecondReq {
    archived     boolean
    id           number
    artImage     string
    postingDate  string
    articleTitle string
}

After I got data, I tried to assign recived data with diferend variable names to unified object but think I did it wrong and got TS errors.获得数据后,我尝试将具有不同变量名称的接收数据分配给统一的 object,但认为我做错了并得到了 TS 错误。 Component code:组件代码:

interface ItemInterface {
  id: number,
  title: string,
  date?: string,
  image?: string,
}

type Item = ItemInterface[]

const Items: React.FC = () => {
  const [itemsData, setItems] = useState<Item>()

  useEffect(() => {
    Http.get<Item>(url).then((res: Item) => setListItems(res))
  }, [])

  if (typeof (itemsData) !== 'undefined') {
    const unifiedItem: Item = {
      id: itemsData.id, // TS error -  TS2339: Property 'id' does not exist on type 'Item'
      title: itemsData.newsTitle || itemsData.articleTitle, // same ERR
      date: itemsData.publishDate || itemsData.postingDate,
      image: itemsData.newsImage || itemsData.artImage,
    }
  }

  const itemsList = () => {
    if (typeof (itemsData) !== 'undefined') {
      return unifiedItem.map((item:{
        id:number, title:string, image?:string
      }) => {
        return (
          <li key={item.id}>
            <ItemPreview item={item} />
          </li>
        );
      })
    }
    return (
      <div></div>
    )
  }

  return (
      <ul>
        {itemsList()}
      </ul>
  )
}

export default Items

main Question is how I can asign recived data to unified object "unifiedItem"?主要问题是如何将接收到的数据分配给统一的 object “unifiedItem”?

Your type Item is defined as an ItemInterface array.您的类型Item被定义为ItemInterface数组。 You can't retrieve an id from an entire array, you have to specified an index in order to retrive an ItemInterface typed element.您无法从整个数组中检索 id,您必须指定索引才能检索ItemInterface类型的元素。

For example: itemsData[0].id should not throw any error !例如: itemsData[0].id不应该抛出任何错误!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM