Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

javascript - How to fix Interface and type?

I try to write component, that should get data with diferent variable names from api and render 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. 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"?

question from:https://stackoverflow.com/questions/65832154/how-to-fix-interface-and-type

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your type Item is defined as an ItemInterface array. You can't retrieve an id from an entire array, you have to specified an index in order to retrive an ItemInterface typed element.

For example : itemsData[0].id should not throw any error !


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...