使用对象映射与扩展运算符返回对象时类型不匹配问题求助
问题原因分析
pool可能为null:Prisma的findFirst方法返回类型是Pool | null,如果查询不到对应数据,pool会是null值,此时this.poolMapper.map(pool)大概率返回空对象或undefined,导致扩展后的对象仅包含voteCounts和votedAnswerId,缺少getPoolResult要求的PoolData相关属性。poolMapper.map返回类型未明确标注:TypeScript无法自动推断map方法返回的是符合PoolData结构的对象,因此认定扩展后的对象仅包含新增的两个属性,不符合getPoolResult的类型约束。
解决方法
1. 处理pool为null的边界情况
先判断查询结果是否存在,避免后续处理null值:
public async getPool({ id, voterId }: { id: string; voterId: string }): Promise<{ pool: getPoolResult }> { const pool = await prisma.pool.findFirst({ where: { id }, include: { answers: { include: { votes: true } } }, }) if (!pool) { throw new Error('Pool not found'); // 也可返回符合类型的默认值 } // ... 其他逻辑计算voteCounts和votedAnswerId return { pool: { ...this.poolMapper.map(pool), voteCounts, votedAnswerId: votedAnswerId as string | null, }, } }
2. 明确poolMapper.map的返回类型
确保map方法的返回值被标注为PoolData,示例如下:
class PoolMapper { // 明确参数为Prisma查询返回的Pool类型,返回值为PoolData map(pool: Prisma.PoolGetPayload<typeof poolInclude>): PoolData { return { id: pool.id, question: pool.question, expiresAt: pool.expiresAt, answers: pool.answers.map(ans => ({ id: ans.id, value: ans.value })), isPublic: pool.isPublic, password: pool.password }; } }
其中poolInclude对应你查询时使用的include配置,保证参数类型准确。
3. 兜底方案:类型断言(仅类型推断失效时使用)
如果map方法逻辑正确但TypeScript仍无法推断类型,可通过类型断言强制标注:
return { pool: { ...(this.poolMapper.map(pool) as PoolData), voteCounts, votedAnswerId: votedAnswerId as string | null, }, }
关于扩展运算符的使用
完全可以使用扩展运算符...合并poolMapper.map的结果和新增属性,只要map方法返回的是符合PoolData结构的对象,扩展后会自动包含所有PoolData属性,再加上voteCounts和votedAnswerId就能完全匹配getPoolResult的类型。
内容的提问来源于stack exchange,提问作者IvonaK
相关产品推荐
相关产品推荐

