The data retrieved from the function is classified as an indeterminate type - functions version 9

I'm currently working with a cloud function that takes an email as input and then returns the user information, which includes the uid.

The declaration of the function looks like this:

const getUserByEmail = httpsCallable(functions, 'getUserByEmail')
const user = await getUserByEmail({
    email: email,
})

However, when I attempt to access "user.data.id," TypeScript gives me an error message stating:

"Object is of type 'unknown'.ts(2571) (property)

HttpsCallableResult.data: unknown Data returned from callable function.

I am unsure of what I may be overlooking in this situation. Any insights or suggestions would be greatly appreciated.

Edit: I did try using "user: any" and TypeScript accepted it, but I know it's not the best solution.

Answer №1

Make sure to provide type information for httpsCallable.

Define the types for RequestData and ResponseData when using httpsCallable.

const fetchUserByEmail = httpsCallable<{email: string}, {
  user: {
    data: {
      id: string,
    }
  }
}>(functions, 'getUserByEmail');

const { data } = await fetchUserByEmail({
    email: email,
});

const userId = data.user.data.id;

Answer №2

TS is unfamiliar with the concept of a user. To address this, you must create a user type guard.

Refer to the example in the documentation to see how TS interprets types in each if statement:

function f(x: unknown) {
  if (typeof x === "string" || typeof x === "number") {
    x; // string | number
  }
  if (x instanceof Error) {
    x; // Error
  }
  if (isFunction(x)) {
    x; // Function
  }
}

For your specific issue, you may need something like this:

export const isUser(x: any): x is User {
  // Check the properties here to ensure that x is indeed a user
}

For further details, refer to https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards

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

Issue with parameter in Angular 2 component

I've encountered an error when attempting to add a service to the constructor of a component. The specific error message I'm receiving is "Can't resolve all parameters for RecordComponent". Any insights into why adding the service to the con ...

What is the most efficient way to fetch only the newly updated child data from a Firebase database?

I have successfully retrieved all child nodes from the Firebase database. Firebase firebase = new Firebase("https://myfiebase-url.firebaseio.com/"); firebase.addValueEventListener(new com.firebase.client.ValueEventListener() { @Override ...

What's the reason for Webstorm's Angular (TSLINT) alert when the attribute "_id" is defined in the model?

Currently I am working on a MEAN app, where I aim to define the user "_id" in my model as per MongoDB/Mongoose standards. I wish for properties like "id" to be as transparent as possible, however there seems to be an issue." According to tslint, variable ...

Creating an interface for a class instance through the implementation of a class constructor

I am working on an application where developers can specify which component they want to render a certain part. I need users to understand that they must implement an interface, but I'm struggling with correctly writing the typing. export interface I ...

I have a quick question: What is the most effective method for creating PDF templates with Angular and .NET 6, specifically for designs that feature heavy

Seeking the optimal solution for creating PDF templates using Angular and .NET 6? Specifically looking to design templates that heavily feature tables. In my exploration of efficient PDF template creation with Angular and .NET 6, I ventured into using pdf ...

Angular2-starter configuration setup with environment-based variables (such as .env or .conf) for testing and production settings

Frameworks like PHP Laravel often include files for local configuration, separate from dev, test, and production environments. How can a configuration file be provided for an angular-starter project that contains all local environment variable values (su ...

Uploading files using Remix.run: Transforming a File object into a string during the action

I'm currently developing a Remix application that allows users to upload files through a form. I have a handler function for handling the form submission, which takes all the form data, including file attachments, and sends it to my action. The probl ...

What is the proper method for verifying token payloads using passport-jwt?

Currently in the process of incorporating passport-jwt into my project, I have a method that generates tokens containing the user's key using jwt-simple. async createToken(u: string, p: string){ let user = await this.us.model.findOne({'key&a ...

Interfaces in Typescript

In my Angular 2 project, I am working on creating an interface for a complex object. Here is the code snippet of the object: // Defining the render state object this.aRenderState = { model: "", colour: false, showWireframe: false, showGrid: true, ...

What could be the possible reason for the token having a null value during login authentication in

As a beginner to Angular, I am facing an issue with my JWT login page implementation. Despite printing the token in the console and confirming its existence as a string, I am receiving a null (or undefined) value. This is the code snippet from my UserServi ...

Using Typescript with MongoDB's JSON schema

Exploring the usage of MongoDB's $jsonschema validator with npm's json-schema-to-typescript has me intrigued. However, I've noticed that MongoDB utilizes bsontype instead of type, which may introduce additional differences that are currently ...

The function item$.take cannot be found, resulting in a TypeError: "item$.take is not a function"

I am currently facing an issue with the take(1) function not working as expected with my Angular Firebase object. I have tried using valuechanges and snapshotchanges as alternatives, but they do not solve the problem for me due to other issues I encounter. ...

Setting up users with email and phone provider via Admin Firebase

Is it possible to create a user with both phone number and email as providers in Firebase? Currently, the provided code only includes the setup for the phone number as the sole provider. https://i.sstatic.net/D7w0O.png admin.auth().createUser({ uid: em ...

What is the significance of incorporating react context, createContext, useContext, and useStore in Mobx?

In my Typescript application, I rely on Mobx for persistence and have created a singleton class called MyStore to manage the store: export class MyStore { @observable something; @observable somethingElse; } export myStore:MyStore = new MyStore(); ...

Is it possible to assign an interface as an argument of an arrow function?

Here is the code I have written: interface ImyInterface { v: number; } class A implements OnInit { ngOnInit() { let myObservable$ = getObs(); myObservable$.subscribe(data => { const foo = data as ImyInterface; ...

Efficiently managing desktop and mobile pages while implementing lazy loading in Angular

I am aiming to differentiate the desktop and mobile pages. The rationale is that the user experience flow for the desktop page involves "scrolling to section", while for the mobile page it entails "navigating to the next section." The issue at hand: Desk ...

Tips for creating an efficient folder structure for your Angular 6 project that can easily scale

Exploring the ins and outs of Angular 6 and its fundamental components has left me with a bit of confusion regarding the ideal folder structure to employ. I've delved into various tutorials from sources like Traversy Media, Udemy, and beyond, each adv ...

Sharing references in React Native using TypeScript: The (property) React.MutableRefObject<null>.current is potentially null

I'm working on a React Native form with multiple fields, and I want the focus to move from one field to the next when the user validates the input using the virtual keyboard. This is what I have so far: <NamedTextInput name={&apo ...

Using RxJs in an Angular 2 application to enable row selection in a table by detecting mouse movements

Check out this example of an Angular 2 application with row selection in a table: https://plnkr.co/edit/HdQnWqbg9HloWb4eYGHz. The row selection functionality is implemented using mouse event handlers (mousedown, mousemove, mouseup). Below is the template ...

Triggering an event through a shared messaging service to update the content of a component

I'm looking for a simple example that will help me understand how I can change the message displayed in my component. I want to trigger a confirmation box with *ngIf and once I confirm the change, I want the original message to be replaced with a new ...