map fungsi
adalah untuk array, jadi saya akan menganggap products Anda kunci dalam contoh Anda adalah array dan bukan objek.
Pertama, saya sarankan Anda menulis definisi jenis dengan benar untuk respons produk Anda jika Anda belum melakukannya
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[];
}
Kemudian, untuk mendapatkan Pick mengerjakan satu products objek, Anda dapat mengindeks IResponse antarmuka dengan menggunakan Jenis Akses yang Diindeks
. Anda menginginkan products properti di index karena ini adalah array.
/*
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"
>
>;
Jika Anda melakukan sesuatu seperti Pick<IResponse["products"], '_id'...> Anda akan mencoba menggunakan Pick untuk mengekstrak properti dari larik, yang akan menghasilkan kesalahan.
Dan satu-satunya yang tersisa adalah memetakan produk dari respons ke bentuk objek yang diinginkan.
// Query your products
const { products }: IResponse = {
_id: "611e2febb863ce74ac448220",
products: [
{
_id: "6116a9ecc3e98d500c5e523d",
category: 5,
gender: 1,
title: 'sivdosi',
description: 'oisbdvoi',
price: 2394,
imageFileName: 'https://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
}));
Hasil akhirnya terlihat seperti berikut
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: 'https://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
}));