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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…