You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript报错Type 'unknown' is not assignable to type解决方法

报错原因

React Router v6 版本中,useLocation 钩子返回的state属性默认类型为unknown,TypeScript 不允许将unknown类型直接赋值给自定义接口类型,因此触发Type 'unknown' is not assignable to type类型报错。

修复方案
  • 方案1:泛型传参(官方推荐写法)
    useLocation 支持传入泛型参数,手动指定state的预期类型。需要注意:用户直接输入路由地址访问页面时,不会携带跳转时传递的state,此时state值为null,需要做兼容兜底:
import { useLocation } from "react-router-dom";

interface UserState {
  status: string;
  id: string;
}

export default function Details() {
  // 泛型指定state类型,同时兼容null场景
  const location = useLocation<UserState | null>();
  // 空值兜底,避免运行时访问属性报错
  const user = location.state ?? { status: "guest", id: "" };
  console.log(user.id);
}
  • 方案2:类型断言(确定state必传时使用)
    如果业务逻辑可以保证,进入该组件的所有路由跳转都一定会传递符合UserState结构的state,可以使用类型断言直接指定类型,跳过TS的静态检查:
import { useLocation } from "react-router-dom";

interface UserState {
  status: string;
  id: string;
}

export default function Details() {
  const location = useLocation();
  // 类型断言指定state类型
  const user = location.state as UserState;
  console.log(user.id);
}

风险提示:类型断言会绕过TypeScript的类型校验,如果实际场景中存在未传state的访问路径,运行时访问user.id会触发Cannot read properties of null错误,非确定场景下不推荐使用。

内容的提问来源于stack exchange,提问作者Malik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 15:27:17