如何使用不变变量作为键创建React导航路由参数TS类型?
使用常量定义React导航路由参数类型报错解决办法
问题背景
想要为React导航路由参数定义如下类型:
export type RootStackParamList = { "Welcome": undefined; "Onboarding User": { category: string }; }
但希望通过常量而非直接字符串作为类型键,于是尝试以下代码:
interface path { [key: string]: string } export const PATHS: path = { welcome: 'Welcome', onboardingUser: "Onboarding User", }; export type RootStackParamList = { [PATHS.welcome]: undefined; [PATHS.onboardingUser]: { category: string }; }
此时触发TypeScript错误:TS1170: A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.
需要实现用不变变量创建对应接口/类型的方法。
解决方案
问题根源在于PATHS被标注为path接口类型,导致TypeScript丢失了属性值的具体字面量类型,仅识别为宽泛的string类型。要保留字面量类型并实现需求,需做以下调整:
方法一:保留路由名字面量作为类型键
// 用as const断言锁定字面量类型,同时禁止修改PATHS export const PATHS = { welcome: 'Welcome', onboardingUser: "Onboarding User", } as const; // 提取PATHS中所有值的字面量类型作为类型键,匹配对应参数 export type RootStackParamList = { [K in typeof PATHS[keyof typeof PATHS]]: K extends typeof PATHS.welcome ? undefined : K extends typeof PATHS.onboardingUser ? { category: string } : never; }
方法二:用PATHS的键名作为类型键
如果希望类型键与PATHS的属性名(如welcome)对应,而非路由显示名(如Welcome),可使用以下写法:
export const PATHS = { welcome: 'Welcome', onboardingUser: "Onboarding User", } as const; export type RootStackParamList = { [K in keyof typeof PATHS]: K extends 'welcome' ? undefined : K extends 'onboardingUser' ? { category: string } : never; }
核心原理
as const断言强制TypeScript将PATHS的属性值识别为不可变的字面量类型,而非宽泛的string- 通过
typeof PATHS[keyof typeof PATHS]提取所有路由名字面量,作为类型的键 - 条件类型精准匹配每个路由对应的参数类型,确保类型安全
内容的提问来源于stack exchange,提问作者Dylan w
相关产品推荐
相关产品推荐

