2

I have a cloud function that takes an email and returns the user info, including the uid.

The function is declared like this:

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

But when I try to read "user.data.id" typescript yells at me because:

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

HttpsCallableResult.data: unknown Data returned from callable function.

What am I missing?

edit: of course I tried "user: any" and TS is happy, but it's not a great solution.

2 Answers 2

1

httpsCallable needs type info.

httpsCallable<RequestData, ResponseData>

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

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

const userId = data.user.data.id;
Sign up to request clarification or add additional context in comments.

Comments

0

TS doesn't know what user is. You would have to implement a user type guard.

check out example from docs how TS understands types in each if branch:

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 problem something like:

export const isUser(x: any): x is User {
  //here you have to check out props so you are sure x is user
}

for more info check out https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.