typescript 如何修复此表达式不可调用,类型“Boolean”没有调用签名

pinkon5k  于 2023-02-17  发布在  TypeScript
关注(0)|答案(1)|浏览(336)

我只是试着检查'USER_ADMIN'是否存在于user.roles中,该代码在Node.js中可以完美地工作,但是当我进入我的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;

这段代码在Node.js中运行得很好,但在react TypeScript中却显示了这个错误。

xuo3flqw

xuo3flqw1#

src/context/AuthContext.tsx:24:34isAdminconst [isAdmin, setIsAdmin] = useState(false);中的函数,而不是另一个文件qrsngky中的函数

相关问题