【发布时间】:2022-02-06 11:25:13
【问题描述】:
我正在使用nestJS,
我有 2 项服务,
在1st service:
async getOrganizations (attributes: (keyof Organization)[]): Promise<Partial<Organization>[]> {
const organizations = await this.organizationRepository.find({select: attributes})
return organizations;
//returns [{id:1, name: "x"},{id:2, name: "y"},..]
}
在2nd service:
async getOrganizations(): Promise<CustomerResponseDto[]> {
const attributes : (keyof Organization)[] = ['id', 'name'];
let organizations = await this.1stService.getOrganizations(attributes);
organizations = organizations.map((organization)=>{
return {
...organization,
type: 'Organization'
}
})
return organizations;
//returns [{id:1, name: "x", type: 'Organization'},{id:2, name: "y", type: 'Organization'},..]
}
还有CustomerResponseDto:
export interface CustomerResponseDto {
readonly id: number;
readonly name: string;
readonly type: string;
}
现在我收到以下错误:
Type 'Partial<Organization>[]' is not assignable to type 'CustomerResponseDto[]'.
Property 'type' is missing in type 'Partial<Organization>' but required in type 'CustomerResponseDto'.
22 | })
23 |
> 24 | return organizations;
| ^^^^^^^^^^^^^^^^^^^^^
25 | }
请指教
【问题讨论】:
-
为什么不指定map回调的返回类型,以便编译器检查:
organizations.map((organization): CustomerResponseDto => ...。为什么要重用已经隐式类型为Partial<Organization>[]的变量? -
非常感谢,这很有帮助,问题与变量命名有关,祝您有愉快的一天
-
请提供足够的代码,以便其他人更好地理解或重现问题。
标签: typescript nestjs