对象的类型未知

问题描述

我正在用离子反应实现打字稿中的jwt身份验证,因此在成功实现它之后,当我要在App.tsx中添加检查时,我在打字时报错

对象的类型为“未知”

这是我的代码

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}

以加密形式存储在我的本地存储中,然后我在此处解码

我收到“对象的类型为'未知'的错误

解决方法

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

有很多方法。如果

  • 您的函数jwt_decode是通用函数。 const解码= jwt_decode (令牌);
  • 或尝试:const decoded : any = jwt_decode(token);

根据您的信息进行更新:

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

const decoded : JWTDeCode = jwt_decode(token);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...