Best way to use select in a function that is returning a specific type

export type UserID = { userID: number }
type UserPassword = { userPassword: string }
type UserFirstName = { userFirstName: string }
type UserLastName = { userLastName: string }
type UserEmail = { userEmail: string }


type IsSuperAdmin = {
isSuperAdmin: boolean | null
}

export type VerifyUser = UserID &
UserFirstName &
UserLastName &
UserEmail &
UserPassword &
IsSuperAdmin & { role: RoleName & RoleID }


export async function verifyUser(email: UserEmail): Promise<VerifyUser | undefined> {
const results: VerifyUser[] | undefined = await db
.select({
userID: users.userID,
userFirstName: users.firstName,
userLastName: users.lastName,
userEmail: users.email,
userPassword: users.password,
isSuperAdmin: users.isSuperAdmin,
role: {
roleID: roles.roleID,
roleName: roles.roleName,
},
})
.from(users)
.innerJoin(roles, eq(users.roleID, roles.roleID))
.where(and(eq(users.email, email.userEmail)))
return results[0] ? results[0] : undefined
}
export type UserID = { userID: number }
type UserPassword = { userPassword: string }
type UserFirstName = { userFirstName: string }
type UserLastName = { userLastName: string }
type UserEmail = { userEmail: string }


type IsSuperAdmin = {
isSuperAdmin: boolean | null
}

export type VerifyUser = UserID &
UserFirstName &
UserLastName &
UserEmail &
UserPassword &
IsSuperAdmin & { role: RoleName & RoleID }


export async function verifyUser(email: UserEmail): Promise<VerifyUser | undefined> {
const results: VerifyUser[] | undefined = await db
.select({
userID: users.userID,
userFirstName: users.firstName,
userLastName: users.lastName,
userEmail: users.email,
userPassword: users.password,
isSuperAdmin: users.isSuperAdmin,
role: {
roleID: roles.roleID,
roleName: roles.roleName,
},
})
.from(users)
.innerJoin(roles, eq(users.roleID, roles.roleID))
.where(and(eq(users.email, email.userEmail)))
return results[0] ? results[0] : undefined
}
I don't understand why this code works. It doesn't return something of type VerifyUser yet the type checker doesn't complain. I am getting:
{
userID: 1,
}

{
userID: 1,
}

Instead of:
{
userID: {userID: 1},
}
{
userID: {userID: 1},
}
1 Reply
Huge Letters
Huge Letters8mo ago
if users.userID is a column on users table then select works correctly - it returns user id(1) on the field userID select returns an array of values - you take the first one. seems correct.
await db.select({ userID: users.userID }) // Array<{userID: number }>
await db.select({ userID: users.userID }) // Array<{userID: number }>
Want results from more Discord servers?
Add your server