First problem- Your function is async
, it returns a promise, so you need to wrap Iuser
inside a promise type-
// NOTE: This code doesn't work just yet, there are more issues
export const existingUser = async (email: string): Promise<Iuser> => {
const foundUser = await User.findOne({ email: email });
return foundUser;
};
Second and main problem - If you check the return type of .findOne
- you'll notice it returns a union type - Either the document that it found or null
(in case your query does not match anything).
This means the type of foundUser
is really, Iuser | null
, but you're treating it as Iuser
- which is not compatible.
What you can do instead is-
export const existingUser = async (email: string): Promise<Iuser | null> => {
const foundUser = await User.findOne({ email: email });
return foundUser;
};
Which will also return either Iuser | null
.
Or if you're 100% certain the user must exist-
export const existingUser = async (email: string): Promise<Iuser> => {
const foundUser = await User.findOne({ email: email });
return foundUser!;
};
The !
operator asserts the type is not null.
Or, if you'd like throw an exception when the user is not found-
export const existingUser = async (email: string): Promise<Iuser> => {
const foundUser = await User.findOne({ email: email });
if (!foundUser) {
throw new Error('User not found');
}
return foundUser;
};
Check out using mongoose with typescript to get a general understanding about how to bake your Iuser
type directly into your mongoose model - which will let the type system do all the type inferring work for you in this case.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…