Error TS2339: The 'email' property is not found in the 'FindUserProps' type

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
}

I am experiencing an issue with the TS2339 error stating that 'Property 'email' does not exist on type 'FindUserProps'. Can anyone help explain why this is happening?

Answer №1

The reason for this behavior is that FindUserProps can only be either FindUserEmailProps or FindUserIdProps, not both simultaneously (which would require both FindUserEmailProps & FindUserIdProps). Therefore, TypeScript needs an assertion to determine which type it is.

In order to extract the email property from a FindUserProps, you must create your own type guard function to help TypeScript identify whether it's a FindUserEmailProps or FindUserIdProps.

// Custom type guard to specify if an object is FindUserEmailProps
function isFindUserEmailProps(obj: FindUserProps): obj is FindUserEmailProps {
  return "email" in obj;
}

export const findUserByEmail = async (userProps: FindUserProps): Promise<IUser> => {
   // Ensure userProps is of type FindUserEmailProps
   if (!isFindUserEmailProps(userProps)) {
      // To simplify, consider changing the function to accept only 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
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implement Stripe API mocking using Jest in Node.js with Typescript

I'm having trouble simulating the Stripe API for testing purposes. Although I don't have much experience with mocking functions using jest, I've already extensively researched how to mock the Stripe API without success. My file structure is ...

Connect the child content to the form

Are there any methods to connect a projected template (ContentChild) to the form specified on the child, such as adding formControlName after it has been rendered? I am having difficulty in finding relevant information online, possibly due to using incorr ...

Encountering the error message "Uncaught Promise (SyntaxError): Unexpected end of JSON input"

Below is the code snippet I am using: const userIds: string[] = [ // Squall '226618912320520192', // Tofu '249855890381996032', // Alex '343201768668266496', // Jeremy '75468123623614066 ...

Can you please explain the significance of classes <T> and <U> in Angular 2?

After diving into the Angular 2 TypeScript documentation, I have come across these two classes frequently. Can someone provide a detailed explanation of what they are? One example code snippet from the QueryList API documentation showcases: class QueryLi ...

SyntaxError in ExpressJS: Encountered an unexpected token "C"

I'm having trouble saving my string to a comma-separated array. When I attempt to use the JSON.parse method, I encounter an error while sending a post request and trying to save a record: SyntaxError: Unexpected token c at Object.parse (native) ...

How can you create an interface where the value type is determined by the key, but not all keys are predefined?

Below is an illustration of a data structure that I aim to define as a type in TypeScript: const dataExample = { Folder: { "Filename.js": { lines: { total: 100, covered: 80, ...

Locate all instances of first or last names using a single query in MongoDB

I need to search my database for occurrences based on a user's input of a first name or last name. I want to return all individuals whose first name or last name matches the query entered by the user. While I already have a solution in place, I belie ...

Issue TS2769: No matching overload found for this call. The type 'string | null' cannot be assigned to type 'string | string[]'

export class AuthService { constructor(private http: HttpClient, private webService: WebRequestService, private router: Router) { } login(email: string, password: string) { return this.webService.login(email, password).pipe( shareReplay(), ...

Mongoose and the concept of floating point values

My latitude and longitude numbers are being converted to strings. However, my section integers remain as the correct data type of Number. How can I adjust my model to retrieve lat and lng as Float instead of String? I am storing latLng data in my database ...

Middleware in Expressjs ensures that variables are constantly updated

I'm attempting to accomplish a straightforward task that should be clear in the code below: module.exports = function(req, res, next) { var dop = require('../../config/config').DefaultOptions; console.log(require('../../config/ ...

Problem with dynamic page routes in Next.js (and using TypeScript)

Hi everyone, I'm currently learning next.js and I'm facing an issue while trying to set up a route like **pages/perfil/[name]** The problem I'm encountering is that the data fetched from an API call for this page is based on an id, but I wa ...

Setting configuration files in Node.js with npm configuration

I have developed a SAAS application on the Angular/NodeJS/Postgres+MongoDB stack that can establish connections with customer databases, cloud warehouses, S3 buckets, and more to load relevant information. Once I receive connection details from the Angular ...

What methods are available for managing errors in express at a global level without relying on try and catch blocks within my controllers

I'm just starting out with Express and I'm wondering if there is a way to implement a global error handler. I'm currently working on a project with a lot of controllers already set up, so it would be cumbersome to add try and catch blocks to ...

The specified type '{ state: any; dispatch: React.Dispatch<{ type: string; value: any; }>; }' is not compatible with the expected type

I've been working on a UI layout that includes checkboxes on the left, a data table on the right, and a drop zone box. The aim is to keep the table data updated whenever a new file is dropped, and also filter the data based on checkbox selection. I ma ...

Converting typescript path aliases into local file paths

Just dipping my toes into typescript and grappling with module resolution. The problem seems straightforward (or so I think), but there's something off about my tsconfig.json. If my folder structure looks like this: + release + definitions + ...

What is the best way to reduce the size of TypeScript source code in an Electron application with the help of Electron Forge and Electron Packager

resolved: I was able to solve this issue using electron-builder, which utilizes webpack in the background to handle all problems efficiently. Initially, I faced this challenge while using electron-forge and electron-packager. Despite researching extensivel ...

What could be causing the issue with creating new comments in my node.js application?

I am encountering an issue while attempting to add a new comment in my node.js application. Specifically, I am trying to create a comment under specific posts using the post's path. Below are the relevant parts of my code: Comment Model const mongo ...

Are you struggling with perplexing TypeScript error messages caused by a hyphen in the package name?

After creating a JavaScript/TypeScript library, my goal is for it to function as: A global variable when called from either JavaScript or TypeScript Accessible via RequireJS when called from either JavaScript or TypeScript Complete unit test coverage Th ...

Tips on transitioning a Node.js application from JavaScript to TypeScript incrementally

I have a JavaScript node application that has grown quite large and I am considering migrating to TypeScript for faster development and easier code maintenance. I have installed TypeScript along with the node and mocha types using the following commands: ...

Displaying notification in Ionic 2

Whenever I click on the register button, if I fill out all the fields I am taken to the regsuccess page. Otherwise, I receive a message saying to fill in all required fields. However, I want to display an alert message using Ionic2 and TypeScript. HTML: ...