I work with three different interfaces
interface A {
productId: string;
productName?: string;
quantity: number;
}
interface B {
productId: string;
productName?: string;
company: string;
}
interface Product {
id: string;
name: string;
In my data structure, I have arrays defined for each interface. For example, here is an array for the Product interface:
[{productId: '1', productName: 'pen', productId: '2', productName: 'paper'}]
The goal is to iterate through the arrays of type A and B, filter to locate the corresponding product in the Product array, and append it to each item. Here's the function attempted:
const addProductNameToLineItem = (
products: Product[],
items: A[] | B[]
): A[] | B[] => {
return items.map((item) => {
const productInfo = products?.find(
(product: Product) => product.id === item?.productId
);
return {
...item,
productName: productInfo?.name
};
});
};
Currently encountering a type error where the result is not assignable to type A[] | B[]. An attempt was made using function overloading without success.
Upon splitting the function into duplicates expecting only type A or B items separately, the operation works as intended.