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
}
在電子郵件屬性中,我得到了 TS2339:“FindUserProps”型別上不存在屬性“電子郵件”這是為什么?
uj5u.com熱心網友回復:
那是因為FindUserProps可以是其中之一FindUserEmailProps或FindUserIdProps但不是兩者(那將是FindUserEmailProps& FindUserIdProps)。這意味著 TypeScript 在您斷言之前不知道它是哪一個。
您的函式必須采用 aFindUserProps并且需要添加您自己的型別保護以讓 TypeScript 知道它是 aFindUserEmailProps還是FindUserIdProps在您可以提取email屬性之前。
// 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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/466376.html
