TS2339: 属性 'email' 在类型 'FindUserProps' 上不存在

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
}

通过电子邮件 属性 我收到了 TS2339:属性 'email' 在类型 'FindUserProps' 上不存在 这是为什么?

那是因为 FindUserProps 可以是 FindUserEmailPropsFindUserIdProps 之一,但不能同时是两者(即 FindUserEmailPropsFindUserIdProps)。这意味着 TypeScript 在您断言之前不知道它是哪一个。

您的函数必须采用 FindUserProps 并且需要 to add your own type guard 让 TypeScript 知道它是 FindUserEmailProps 还是 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
}