'Data from function is of type unknown - functions v9
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.
Solution 1:[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;
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Isamu Arimoto |
Solution 2 | kit |