El map
función
es para arreglos, así que asumiré sus products
la clave en su ejemplo es una matriz y no un objeto.
Primero, le sugiero que escriba correctamente las definiciones de tipo para la respuesta de sus productos si aún no lo ha hecho
interface IProduct {
_id: string,
category: number,
gender: number,
title: string,
description: string,
price: number,
imageFileName: string,
createdAt: string,
updatedAt: string,
__v: number
}
interface IResponse {
_id: string;
products: IProduct[];
}
Luego, para obtener Pick
trabajando en un único product
objeto, puede indexar el IResponse
interfaz usando Tipos de acceso indexado
. Quiere los products
propiedad en un index
porque es una matriz.
/*
Indexed Access Types
type Person = { age: number, name: string }[];
type Age = Person[number]["age"];
*/
type Products = ReadonlyArray<
Pick<
IResponse["products"][number],
"_id" | "gender" | "title" | "description" | "price" | "imageFileName"
>
>;
Si tuviera que hacer algo como Pick<IResponse["products"], '_id'...>
estarías tratando de usar Pick
para extraer propiedades de una matriz, lo que daría como resultado un error.
Y lo único que queda es mapear los productos de la respuesta a la forma del objeto deseado.
// Query your products
const { products }: IResponse = {
_id: "611e2febb863ce74ac448220",
products: [
{
_id: "6116a9ecc3e98d500c5e523d",
category: 5,
gender: 1,
title: 'sivdosi',
description: 'oisbdvoi',
price: 2394,
imageFileName: 'http://localhost:3000/images/1628875244435-3564.png',
createdAt: "2021-08-13T17:20:44.472Z",
updatedAt: "2021-08-13T17:20:44.472Z",
__v: 0
}
]
}
// Get the desired object
const pickedProducts: Products = products.map(({ _id, gender, title, description, price, imageFileName }) => ({
_id,
gender,
title,
description,
price,
imageFileName
}));
El resultado final se parece a lo siguiente
interface IProduct {
_id: string,
category: number,
gender: number,
title: string,
description: string,
price: number,
imageFileName: string,
createdAt: string,
updatedAt: string,
__v: number
}
interface IResponse {
_id: string;
products: IProduct[];
}
type Products = ReadonlyArray<
Pick<
IResponse["products"][number],
"_id" | "gender" | "title" | "description" | "price" | "imageFileName"
>
>;
// Query your products
const { products }: IResponse = {
_id: "611e2febb863ce74ac448220",
products: [
{
_id: "6116a9ecc3e98d500c5e523d",
category: 5,
gender: 1,
title: 'sivdosi',
description: 'oisbdvoi',
price: 2394,
imageFileName: 'http://localhost:3000/images/1628875244435-3564.png',
createdAt: "2021-08-13T17:20:44.472Z",
updatedAt: "2021-08-13T17:20:44.472Z",
__v: 0
}
]
}
// Get the desired object
const pickedProducts: Products = products.map(({ _id, gender, title, description, price, imageFileName }) => ({
_id,
gender,
title,
description,
price,
imageFileName
}));