使用枚举时出现TypeScript错误:string无法赋值给never类型
问题原因
你遇到的TypeScript错误,核心是类型信息丢失:
- 把两个枚举展开到类型为
{ [key: string]: string }的Routes对象后,TypeScript会将所有属性值的类型收窄为宽泛的string,而非保留枚举成员的具体字面量类型(比如'OakUrl')。 - React Navigation的
navigate方法会根据路由配置推断可接受的路由名称类型,当传入不确定的string时,TypeScript无法确认它属于合法路由,因此抛出Argument of type 'string' is not assignable to parameter of type 'never'错误。
解决方案
以下两种修复方式可按需选择:
方式一:保留枚举的字面量类型(推荐)
修改路由文件,用as const让TypeScript保留每个路由值的具体字面量类型,同时导出联合类型供导航使用:
export enum LoggedInRoutes { OAK_URL = 'OakUrl', PROFILE = 'Profile', ROOT = 'Root', } export enum TestingRoutes { DATA_MANAGEMENT = 'DataManagement', } // 合并枚举并保留字面量类型 export const Routes = { ...LoggedInRoutes, ...TestingRoutes, } as const; // 导出路由名称的联合类型,用于导航类型约束 export type RoutesType = (typeof Routes)[keyof typeof Routes];
在组件中给useNavigation指定路由类型,让navigate识别合法路由:
import * as React from 'react'; import { Button } from 'react-native'; import { useNavigation, NavigationProp } from '@react-navigation/native'; import { Routes, RoutesType } from './Routes'; // 定义导航栈参数列表,根据实际路由参数调整 type RootStackParamList = { [K in RoutesType]: undefined; // 假设所有路由无参数,有参数可单独定义 }; const App = () => { const { navigate } = useNavigation<NavigationProp<RootStackParamList>>(); return ( <Button title={'Go to url'} onPress={() => navigate(Routes.OAK_URL)} /> ); }; export default App;
方式二:调整Routes对象的类型约束
如果不想用as const,可修改Routes的类型为两个枚举的类型合并,避免使用宽泛的string索引:
enum LoggedInRoutes { OAK_URL = 'OakUrl', PROFILE = 'Profile', ROOT = 'Root', } enum TestingRoutes { DATA_MANAGEMENT = 'DataManagement', } // 合并两个枚举的类型 type CombinedRoutes = typeof LoggedInRoutes & typeof TestingRoutes; const Routes: CombinedRoutes = { ...LoggedInRoutes, ...TestingRoutes, }; export default Routes; export type RoutesType = LoggedInRoutes | TestingRoutes;
这种方式下,Routes的每个属性值会保留枚举的具体类型,navigate就能正确识别参数类型,不会再报错。
内容的提问来源于stack exchange,提问作者verunar
相关产品推荐
相关产品推荐

