As a newcomer to TypeScript, I find the concept of type-hinting quite strong but also overwhelming at times. In my TypeScript project using express and Prisma ORM, I've encountered an issue with the result of the findUnique method. Let me elaborate.
In the project, I have a simple user model defined as follows:
// prisma/schema/user.prisma
model User {
id String @id @default(cuid())
firstname String
lastname String
email String @unique
password String
salt String?
sessionToken String? @unique
}
Additionally, I have a helper file that handles various user operations such as getting users and creating them. One specific function in this file retrieves a user by their email:
// src/helpers/users.ts
export const getUserByEmail = (email: string) => prisma.user.findUnique({
where: { email },
})
Moreover, there is a controller for the login action which involves retrieving the user by email and verifying the password hash:
// src/controllers/authentication.ts
export const login = async (req: express.Request, res: express.Response) => {
try {
const { email, password } = req.body
if (!email || !password) {
res.sendStatus(HttpStatus.BAD_REQUEST)
}
let user = await getUserByEmail(email)
if (!user) {
return res.sendStatus(HttpStatus.BAD_REQUEST)
}
const expectedHash = authentication(user.salt, password)
// ...
return res.status(HttpStatus.OK).json(user).end()
} catch (error) {
console.error(error)
return res.sendStatus(HttpStatus.BAD_REQUEST)
}
}
The problem arises when I try to access user.salt
and receive an error stating unresolved variable salt. I attempted to specify that I expect a User object as the response but it didn't work out:
import { User } from '@prisma/client'
// ...
let user: User | null = await getUserByEmail(email)
However, I'm presented with a lengthy error message noting that Initializer type Prisma__UserClient<$Result.GetResult<Prisma.$UserPayload<$Extensions.DefaultArgs>, {where: {email: string}}, "findUnique"> | null, null, $Extensions.DefaultArgs> is not assignable to variable type User | null
Given this complex error with numerous subtypes and variables, I'm feeling a bit lost. Can someone please shed light on what I might be missing here?