I've encountered a type mismatch error in my TypeScript project using Prisma while attempting to return an object with mapped properties in the getPool
method.
Let's take a look at the code snippet causing the issue:
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 } } },
})
// ...
return {
pool: {
...this.poolMapper.map(pool),
voteCounts,
votedAnswerId: votedAnswerId as string | null,
},
}
}
Now let's review the defined types:
export const PoolSchema = z.object({
id: z.string(),
question: z.string().min(MIN_QUESTION_LENGTH).max(MAX_QUESTION_LENGTH),
expiresAt: z.coerce.date(),
answers: z.array(
z.object({
id: z.string(),
value: z.string(),
})
),
isPublic: z.boolean(),
password: z.string().optional(),
})
export type PoolData = z.infer<typeof PoolSchema>
export type VoteCounts = Record<string, number>
export type getPoolResult = PoolData & {
voteCounts: VoteCounts
votedAnswerId: string | null
}
The specific error message I'm facing states:
Type '{ voteCounts: VoteCounts; votedAnswerId: string | null; }' is not assignable to type 'getPoolResult'. Type '{ voteCounts: VoteCounts; votedAnswerId: string | null; }' is missing certain properties from type '{ password?: string | undefined; question: string; expiresAt: Date; answers: { value: string; id: string; }[]; isPublic: boolean; id: string; }': question, expiresAt, answers, isPublic, idts(2322)
Upon letting TypeScript infer the return type, it results in:
Promise<{
pool: {
voteCounts: VoteCounts;
votedAnswerId: string | null;
};
}>
I would greatly appreciate any assistance in understanding why this error occurs and how it can be resolved. It appears there is a discrepancy between the returned object and the expected type.
Additionally, I am curious if it's possible to utilize the rest operator (...)
for the poolMapper
operation within the return statement to encompass all properties from the mapped pool object.