typescript TS -此表达式不可调用,类型“Boolean”没有调用签名

14ifxucb  于 2023-02-13  发布在  TypeScript
关注(0)|答案(1)|浏览(441)

我遇到了一个问题,我只是试图检查user.roles中是否存在"USER_ADMIN",该代码在NodeJS中工作正常,但当我进入我的react-typescript项目时,我得到了这个错误:

src/context/AuthContext.tsx:24:34 - error TS2349: This expression is not callable.
  Type 'Boolean' has no call signatures.

24       let isAdminTest: boolean = isAdmin("ROLE_ADMIN", roles);

我的身份验证上下文位于:

import { createContext, useEffect, useState } from "react";
import { AuthContextType, ChildProps } from "../@types";

const initialState: AuthContextType = {
  isLoggedIn: false,
  isAdmin: false,
  login(username, email, token) {},
  logout() {},
};

const AuthContext = createContext<AuthContextType>(initialState);

const AuthContextProvider = ({ children }: ChildProps) => {
  useEffect(() => {
    const userData = localStorage.getItem("user");
    if (userData) {
      const user = JSON.parse(userData);
      const token = user.token;
      const email = user.email;
      const username = user.username;
      const roles = user.roles;

      //isAdminTest = false/true
      let isAdminTest: boolean = isAdmin("ROLE_ADMIN", roles);
      login(username, email, token);
    }
  }, []);

  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [isAdmin, setIsAdmin] = useState(false);
  const [username, setUsername] = useState<string | undefined>(undefined);
  const [email, setEmail] = useState<string | undefined>(undefined);
  const [token, setToken] = useState<string | undefined>(undefined);

  const login = (username: string, email: string, token: string) => {
    setIsLoggedIn(true);
    setEmail(email);
    setUsername(username);
    setToken(token);
  };

  const logout = () => {
    setIsLoggedIn(false);
    setToken(undefined);
    setEmail(undefined);
    setUsername(undefined);
  };
  //what we want to expose/share with the app:
  const contextValues = {
    isAdmin,
    isLoggedIn,
    username,
    token,
    email,
    login,
    logout,
  };
  return (
    <AuthContext.Provider value={contextValues}>
      {children}
    </AuthContext.Provider>
  );
};

//the provider is only used in index.tsx <Provider>
export { AuthContext, AuthContextProvider };

//used in all the app:
export default AuthContext;

这个函数检查字符串是否存在于数组中

const isAdmin = (string: string, arr: string[]) => {
  let isTrue: boolean = false;
  arr.forEach((value, index) => {
    if (string === value) {
      isTrue = true;
    }
  });
  return isTrue;
};
export default isAdmin;

这段代码在NodeJS中工作得很好,但是在react类型脚本中它说这个错误有什么想法吗?
谢谢!
我尝试到检查如果是管理员

pepwfjgg

pepwfjgg1#

您的源代码/上下文/授权上下文的isAdmin是常量[isAdmin,setIsAdmin] = useState(false)中的一个;,而不是您在另一个文件- qrsngky中的函数21分钟前

相关问题