如何在Typescript中调用这种类型的异步函数

i34xakig  于 2023-01-31  发布在  TypeScript
关注(0)|答案(1)|浏览(112)

如何在onAuthStateChanged中输入异步回调函数?
此行中出现错误“在应返回void的函数参数中返回了Promise。”。

async (user: User | null) => {
  const unpdatedUser = user ? await adminUser(user) : null;
  callback(unpdatedUser);
};

下面是完整的代码。

type DispatchType = Dispatch<SetStateAction<User | null>>;

export function onUserStateChange(callback: DispatchType) {
  onAuthStateChanged(auth, async (user: User | null) => {
    const unpdatedUser = user ? await adminUser(user) : null;
    callback(unpdatedUser);
  });
}

async function adminUser(user: User | null) {
  return get(ref(database, 'admins')).then((snapshot) => {
    if (snapshot.exists()) {
      const admins = snapshot.val();
      const isAdmin = admins.include(user?.uid);
      return { ...user, isAdmin };
    }
    return user;
  });
}
kknvjkwl

kknvjkwl1#

您在Firebase Auth User类型和您自己的User类型(包括一个isAdmin布尔值)之间存在一些类型混淆。
我会选这样的...

import { User as FirebaseUser } from "firebase/auth";

// this is your user type
interface User extends FirebaseUser {
  isAdmin: boolean;
}

在尝试将nulluser参数扩展到{ ...user, isAdmin }之前,还应检查该参数。
adminUser函数应返回类型Promise<User | null>

async function adminUser(user: FirebaseUser | null): Promise<User | null> {
  // null user
  if (!user) {
    return user;
  }

  const isAdmin =
    (await get(ref(database, "admins"))).val()?.include(user.uid) ?? false;
  return { ...user, isAdmin };
}

相关问题