[英]TS2339: Property 'email' does not exist on type 'FindUserProps'
interface FindUserEmailProps {
readonly email: string
}
interface FindUserIdProps {
readonly id: string
}
type FindUserProps = FindUserEmailProps | FindUserIdProps
export const findUserByEmail = async ({ email }: FindUserProps): Promise<IUser> => {
const user = await User.findOne({ email })
if (!user) {
throw new Error('User not found')
}
return user
}
At email property I got TS2339: Property 'email' does not exist on type 'FindUserProps' Why is that?在 email 属性中,我得到了 TS2339:属性“email”在类型“FindUserProps”上不存在这是为什么?
That's because FindUserProps
can be one of FindUserEmailProps
or FindUserIdProps
but it's not both (that would be FindUserEmailProps
& FindUserIdProps
).那是因为FindUserProps
可以是FindUserEmailProps
或FindUserIdProps
之一,但不能同时是两者(即FindUserEmailProps
和FindUserIdProps
)。 That means that TypeScript doesn't know which one it is until you assert it.这意味着 TypeScript 在您断言之前不知道它是哪一个。
Your function has to take a FindUserProps
and needs to add your own type guard to let TypeScript know whether it's a FindUserEmailProps
or FindUserIdProps
before you can extract an email
property.在提取email
属性之前,您的 function 必须采用FindUserProps
并需要添加您自己的类型保护,让 TypeScript 知道它是FindUserEmailProps
还是FindUserIdProps
。
// Custom type guard that lets TypeScript know whether your
// object is a FindUserEmailProps
function isFindUserEmailProps(obj: FindUserProps): obj is FindUserEmailProps {
return "email" in obj;
}
export const findUserByEmail = async (userProps: FindUserProps): Promise<IUser> => {
// You have to make sure it's a FindUserEmailProps
if (!isFindUserEmailProps(userProps)) {
// Since you are just throwing an error, you may as well
// change your function to only accept a FindUserEmailProps
throw new Error("Invalid userProps to find by email");
}
const {email} = userProps;
const user = await User.findOne({ email })
if (!user) {
throw new Error('User not found')
}
return user
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.