对象的类型未知

Object is of type unknown

我在 ionic react with typescript 中实现了 jwt 身份验证,所以在成功实现之后,当我想在我的 App.tsx 中添加支票时,我收到一个 typescript 错误

Object is of type 'unknown'

这是我的代码

const App: React.FC<Idecode> = () => {
  const dispatch = useDispatch();

  if (localStorage.jwtToken) {
    // Set auth token header auth
    const token = localStorage.jwtToken;
    setAuthToken(token);
    // Decode token and get user info and exp
    const decoded = jwt_decode(token);
    console.log(decoded);
    // Set user and isAuthenticated
    dispatch(setCurrentUser(decoded));
    // Check for expired token
    const currentTime = Date.now() / 1000; // to get in milliseconds

    console.log(decoded.exp, currentTime); //Here when i access exp i get an error

    if (decoded.exp < currentTime) {
      // Logout user
      dispatch(logoutUser());

      // Redirect to login
      window.location.href = "./login";
    }
  }

  return (
    <IonApp>
      <IonReactRouter>
        <IonRouterOutlet id="menu">
          <Route path="/signup" component={Signup} exact={true} />
          <Route path="/" component={Home} exact={true} />
          <Route path="/verify" component={Verify} exact={true} />
          <Route path="/login" component={Login} exact={true} />
          <Route
            path="/forgot-password"
            component={forgotPassword}
            exact={true}
          />
          <Route path="/set-password" component={setPassword} exact={true} />
        </IonRouterOutlet>
      </IonReactRouter>
    </IonApp>
  );
};

export default App;

所以当我尝试获取“decoded.exp”(我在实现 jwt 后通过我的后端获取)包含类似

的数据
{id: "5f5f30cdbfd0c11d426245e5", email: "ratnabh2615@gmail.com", iat: 1600085677, exp: 1600172077}

它以加密形式存储在我的localstoage中,然后我在这里解码

我收到错误消息“对象的类型为 'unknown'”

我认为您必须为 const decoded = jwt_decode(token); 显式设置泛型类型才能在访问对象之前知道它的类型。

方法有很多种。如果

  • 您的函数 jwt_decode 是通用函数。常量解码 = jwt_decode<任意| YourDefinedType>(令牌);
  • 或者试试:const decoded : any = jwt_decode(token);

根据您的信息更新:

type JWTDeCode  = {
    id: string,
    email: string,
    iat: number,
    exp: number
}

const decoded : JWTDeCode = jwt_decode(token);