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

Expo+TypeScript中router.push类型错误,求更简洁解决方案

解决 Expo Router 路径常量的 TypeScript 类型错误

针对你遇到的问题,不用逐个给路径常量手动指定类型,有以下几种更高效的处理方式:

方案1:给整个数组指定统一类型

直接给解构的数组添加Href<string | object>[]类型,这样解构出的每个变量都会自动继承正确类型:

import { Href } from 'expo-router';

const [HomePath, SettingsPath, ProfilePath]: Href<string | object>[] = [
  "/",
  "/settings",
  "/profile",
];

router.push(HomePath); // 类型正确

方案2:利用as const和satisfies兼顾类型安全与精确性

如果希望路径被推断为字面量类型(比如"/"而不是泛泛的string),同时确保符合Href类型要求,可以用as const结合satisfies:

import { Href } from 'expo-router';

const [HomePath, SettingsPath, ProfilePath] = [
  "/",
  "/settings",
  "/profile",
] as const satisfies readonly Href<string>[];

这种方式既保留了路径的精确类型(后续如果修改路径写错,TS会直接报错),又不需要逐个标注类型,同时满足router.push的参数要求。

方案3:用对象集中管理路径(推荐用于多路径场景)

把所有路径放在一个常量对象中统一管理,既方便维护,也能一次性处理类型:

import { Href } from 'expo-router';

const AppPaths = {
  Home: "/" as Href<string>,
  Settings: "/settings" as Href<string>,
  Profile: "/profile" as Href<string>,
} as const;

// 使用时直接调用对象属性
router.push(AppPaths.Home);

这种方式的优势在于,后续新增或修改路径只需要在AppPaths里操作,避免分散定义导致的遗漏,类型也能统一保证。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 03:27:04