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
相关产品推荐
相关产品推荐

