swagger - NestJS 映射类型 - 嵌套对象
问题描述
在 NestJS 中,我想PickType()
与一个具有嵌套类属性的类一起使用。
例子:
export class Product {
status: string;
payment: {
status: string;
type: string;
}
}
它应该导致如下 DTO 的招摇文档:
class PartialClass {
payment: {
status: string,
type: string
}
}
但是以下实现不起作用:
class PartialClass {
@ApiProperty({
type: () => PickType(Videochat, ['payment']),
})
payment: Pick<Videochat['payment'], 'type' | 'status'>;
}
它返回一个空的支付类属性:
class PartialClass {
payment: {
}
}
所以我猜 PickType 不能处理嵌套类型。
我也试过:
type: () => PickType(PickType(Videochat, ['payment']), ['status', 'type'])
但它也不起作用。
解决方案
你可以这样处理,假设我们有以下类:
type User = {
id: number,
name: string,
address: {
street: string,
zipcode: string,
geo: {
lat: string,
lng: string,
},
},
};
选择带有地址的用户,你可以简单地做type UserWithOnlyAddress = Pick<User, 'address'>;
如果您必须选择具有地址街道的用户,则只有您可以处理它:
type Pick2<T, K1 extends keyof T, K2 extends keyof T[K1]> = {
[P1 in K1]: {
[P2 in K2]: (T[K1])[P2];
};
};
type UserWithOnlyStreetAddress = Pick2<User, 'address', 'street'>;
并在三个层次上采摘
type UserWithOnlyGeoLat = Pick3<User, 'address', 'geo', 'lat'>;
type User = {
id: number,
name: string,
address: {
street: string,
zipcode: string,
geo: {
lat: string,
lng: string,
},
},
};
type Pick3<T, K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2]> = {
[P1 in K1]: {
[P2 in K2]: {
[P3 in K3]: ((T[K1])[K2])[P3];
};
};
};
推荐阅读
- html - 无法在 main 上放置边距,因为固定的标题和简介会移动
- amazon-web-services - AWS CodeBuild - 如何在 buildspec.yml 中分配动态变量值?
- cuda - 尝试在 Ubuntu 18.04 上安装 CUDA 9.2
- c# - Ajax.ActionLink 替代方案 - Net Core
- java - 如何在视图中显示对象的内容?
- acumatica - Acumatica - 使用不同字段的值填充字段
- java - 我的 AnimationDrawable 对象的 run 方法减慢了我的应用程序,有什么解决方案吗?
- c# - 如何在mailbee LoadMessage的路径中进行连接
- hadoop - HDFS如何在VM上找到主机名端口号
- php - Woocommerce“订单支付”页面 - 显示帐单地址?