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

"Exploring the power of index signatures and methods in Typescript

What might be the reason for code producing a ts(2411) error? class Greeter { [key: string]: string | number[]; greeting: string; constructor(message: string) { this.greeting = message; } greet(): string { return "Hel ...

Having trouble importing a TypeScript module from the global node_modules directory

I have a library folder located in the global node modules directory with a file named index.ts inside the library/src folder //inside index.ts export * from './components/button.component'; Now I am trying to import this into my angular-cli ap ...

Having trouble getting undefined values for keys while attempting to retrieve all the data from Firebase DB with Angular

Currently, I have code that is fetching records from the Firebase database using both Angular and Ionic. The code functions properly, but it does not provide me with the keys for each record. Instead, it returns 'undefined'. I have researched s ...

Import reactjs modules without the need for Browserify, Webpack, or Babel

I am attempting to set up a TypeScript HTML application in Visual Studio. My goal is to incorporate reactjs v0.14.7 without relying on tools like Browserify. But, how can I utilize the react-dom module in this scenario? Let's set aside TypeScript fo ...

Redirecting ports in Node.js

I am currently facing an issue with my two-server setup. One server is dedicated to running a chat application, while the other is responsible for generating APIs (users must register by providing company details and receive an API key from my algorithm). ...

Having trouble converting the response into a valid TypeScript value for storage

These are the interfaces I have described: enum ProductType {current, closed, coming} export interface CurrentProductForCarousel { type_product:ProductType.current; offers: ProductMainInfo[] } export interface ProductMainInfo { id: number; disclai ...

Looking to adjust the API response to fit the necessary JSON format for an Angular project?

A modification is needed in the API response to align with the required JSON format provided below. The current responses and the desired format are detailed for reference. Assistance is appreciated. The current representation of individual's data ne ...

Utilizing a string variable as a property name for dynamic typing

I am looking to dynamically create a type with a property name based on specified parameters. Although I can successfully create the object, I am facing challenges when trying to create the actual type. This dynamic type creation is essential for compositi ...

Generate random entries from an object based on specific criteria and append them to a fresh object using Typescript

Experimenting with Ionic2 and Typescript has been my recent focus. I have an object that contains various meals, calorie counts, and meal types (such as vegan). This is how the object looks: [ { "id":14093, "name":"Proteinshake mit Wasser ...

Monitor the closure of a programmatically opened tab by the user

Currently, I am in the process of developing a web application using Angular 11 that interacts with the msgraph API to facilitate file uploads to either onedrive or sharepoint, and subsequently opens the uploaded file in the Office online editor. Although ...

How to calculate the sum of all values in a FormArray in Angular

I am trying to retrieve the input values from each row and then calculate the sum of these rows. Here is my HTML code: <ng-container formArrayName="cap_values"> <tbody *ngFor="let item of capValues.controls; let i=index" [formGroupName]="i"& ...

Can you share tips for passing a variable from a post request to a function that accepts parameters as a string or an array of strings in Node.js?

I am struggling to insert the variable named query into the end of the prompt. I attempted to use template literals but it was unsuccessful. (async () => { const gbtResponse = await openai.createCompletion({ model: "text-davinci-002", prompt ...

Exploring the creation of an Angular service that utilizes HttpClient for making GET requests, with a focus on the different

I've been diving into Angular lately and I'm facing some challenges with handling get requests. If you're interested, you can check out my code on Angular Stackblitz import { HttpClient} from '@angular/common/http'; import { Inject ...

Number of Active Socket.IO Connections

I've been attempting to retrieve the connection count from the server socket, with the client application set up separately. Despite consulting various Stack Overflow articles that discuss different methods for obtaining socket connection counts, I ha ...

Specialized type for extra restriction on enum matching

In my current project, I am dealing with two enums named SourceEnum and TargetEnum. Each enum has a corresponding function that is called with specific parameters based on the enum value. The expected parameter types are defined by the type mappings Source ...

Encountered a problem when trying to import the function "createToken" into a Node.js middleware

I have developed a model called users in which I included a method named generateToken for generating web tokens. This model is being used with the Sequelize ORM. module.exports = (sequelize, Sequelize) => { const Tutorial = sequelize.define("u ...

Validation of the existence of a MongoDB user

I'm currently working on implementing a sign-up form using Mongo, Node.js, and Express.js. I've managed to successfully insert a document into the users collection for a new user. However, I now need to set up validation to check if a user alread ...

Avoid using cookies for tracking purposes

I've set up basic authentication, which is working fine in my localhost environment. However, when I try to run the same setup in production, the registration process works but the cookie isn't getting assigned to the client site. Client side: ...

Can an enum be declared in Typescript without specifying a type explicitly?

Within an interface, I have a group of 10+ (optional) members, most of which have a specific set of potential values. To streamline this, I would like to utilize enums. However, creating separate enum types for each member (which are only used once and hav ...

Tips for accessing data in express js

Recently, I decided to dive into learning about expressJs and attempted to create a route that would return a simple test sentence as JSON. Unfortunately, I seem to be encountering some issues with my code in expressJs. test.js var express = require(&apo ...