map function 用于数组,因此我假设您的示例中的 products 键是数组而不是对象。
首先,如果您还没有,我建议您正确地为您的产品响应编写类型定义
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[];
}
然后,要让Pick 处理单个product 对象,您可以使用Indexed Access Types 索引IResponse 接口。您希望 products 属性位于 index,因为它是一个数组。
/*
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"
>
>;
如果您要执行Pick<IResponse["products"], '_id'...> 之类的操作,您会尝试使用Pick 从数组中提取属性,这会导致错误。
剩下的唯一事情就是将产品从响应映射到所需的对象形状。
// 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
}));
最终结果如下所示
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
}));