I'm currently developing a feature that fetches a list of products from an E-commerce API and I want to enhance it by allowing users to request specific fields from the products while eliminating any unnecessary ones.
This is the snippet of code in question:
interface Product {
images: string[],
title: string;
id: number;
currency: string;
price: number;
created: string | Date;
description: string;
}
const getProducts = (selectedProperties: (keyof Product)[]) => {
// Assume this is an API call to retrieve a list of products
const products: Product[] = [
{
id: 1,
images: [],
title: 'a shirt',
currency: "USD",
price: 10,
created: "2021-04-29T11:21:53.386Z",
description: "Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."
}
];
if(selectedProperties?.length){
return products.map(product => {
const result: Partial<Product> = {};
selectedProperties.forEach(prop => {
result[prop] = product[prop]; // <--- This line returns the error: Type 'string | number | string[] | Date' is not assignable to type 'undefined'. Type 'string' is not assignable to type 'undefined'
})
return result;
})
}
return products;
}
If you'd like to see the TypeScript error for yourself, here is the link to the code sandbox: link (check line 30)
Can someone help me figure out what mistake I am making here that is leading to the TypeScript error?