【问题标题】:Typescript issue: Type '...' is not assignable to type '...'打字稿问题:类型“...”不可分配给类型“...”
【发布时间】: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 =&gt; ...。为什么要重用已经隐式类型为Partial&lt;Organization&gt;[] 的变量?
  • 非常感谢,这很有帮助,问题与变量命名有关,祝您有愉快的一天
  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: typescript nestjs


【解决方案1】:

现在可以了,问题与变量命名有关 在2nd service 我改变了:

organizations = organizations.map((organization)=>{
            return {
                ...organization,
                type: 'Organization'
            }

成为

const organizationsWithType = organizations.map(({ id, name })=>{
            return {
                id,
                name,
                type: 'Organization'
            }
        })

【讨论】:

    猜你喜欢
    • 2021-10-11
    • 2020-06-29
    • 2019-09-25
    • 2022-08-14
    • 2016-10-25
    • 2018-02-02
    • 2021-06-17
    • 2018-01-04
    • 1970-01-01
    相关资源
    最近更新 更多