[英]Typescript - Function return type if I want to return object
注意:请在回答前通读。 这看起来像一个简单的问题,但我不确定它是否那么简单。 另外,我是 typescript 的新手,所以 go 对我来说很容易:p
所以这里是用例。 我有一个 model 用户,我写了一个通用的 function 来根据数据库中的 email 检查用户是否存在。 如果存在,则返回用户 object。
现在,如果它是任何其他 object,那么我可以定义类型并继续使用我的代码,但它是我从 DB 获得的用户 object,不知道如何解决这个问题。
我通过提到返回类型“any”找到了解决方法,但我的灵魂对此并不平静。 这感觉更像是一个 hack,而不是一个解决方案。
废话不多说,代码如下:
export const existingUser = async (email: string): Promise<any> => {
const foundUser = await User.findOne({ email: email });
return foundUser;
};
现在,正如我上面提到的那样,这是可行的,但我尝试了一种不同的方法,即抛出错误。 我已经定义了我的用户 model 类型,如下所示:
export interface Iuser extends Document {
profile_picture_url?: string;
first_name: string;
last_name: string;
email: string;
password: string;
phone_number?: string;
is_agree_terms_at: string;
gender?: Gender;
role: UserRole;
isValid: boolean;
}
然后提到 Iuser 作为我的返回类型,因为这是我期望从 DB 获得的 object 的类型。 我知道一旦将其添加到数据库中,它将具有其他字段,但我不知道更好-_-
export const existingUser = async (email: string): Promise<Iuser> => {
const foundUser = await User.findOne({ email: email });
return foundUser;
};
请帮帮我。 我无法入睡。
第一个问题-您的 function 是async
的,它返回 promise,因此您需要将Iuser
包装在 promise 类型中-
// 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;
};
第二个也是主要问题 - 如果您检查.findOne
的返回类型 - 您会注意到它返回联合类型 - 它找到的文档或null
(以防您的查询不匹配任何内容)。
这意味着foundUser
的类型实际上是Iuser | null
Iuser | null
,但您将其视为Iuser
- 这是不兼容的。
你可以做的是——
export const existingUser = async (email: string): Promise<Iuser | null> => {
const foundUser = await User.findOne({ email: email });
return foundUser;
};
这也将返回Iuser | null
Iuser | null
。
或者,如果您100% 确定用户必须存在-
export const existingUser = async (email: string): Promise<Iuser> => {
const foundUser = await User.findOne({ email: email });
return foundUser!;
};
或者,如果您想在找不到用户时抛出异常-
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.