如何在TypeScript中正确为react-navigation-v6使用联合类型路由参数
这个问题我之前也碰到过,核心是TypeScript联合类型的类型收窄逻辑,结合react-navigation的类型定义来调整就行,分两种常见场景给你解决方案:
场景1:组件仅对应单个屏幕(最常见)
你的代码里把'TestScreen' | 'TestScreen2'作为泛型参数传给StackScreenProps,导致route.params变成了两个参数类型的联合。如果这个组件只用来渲染TestScreen,直接把泛型参数改成具体的屏幕名称即可,这样TypeScript能明确知道route.params的类型:
import { StackScreenProps } from '@react-navigation/stack' import React from 'react' type TestScreenParamList = { TestScreen: { randomString: string } TestScreen2: { randomString2: string } } // 只指定单个屏幕名称,而非联合类型 type TestScreenStackProps = StackScreenProps<TestScreenParamList, 'TestScreen'> const TestScreen = ({ route, navigation }: TestScreenStackProps) => { console.log(route.params.randomString) // 现在不会有TS错误了 return <></> }
场景2:组件需要处理多个屏幕(复用组件)
如果这个组件要同时兼容TestScreen和TestScreen2,就得用类型守卫来缩小联合类型的范围,告诉TypeScript当前route.params属于哪一种类型:
import { StackScreenProps } from '@react-navigation/stack' import React from 'react' type TestScreenParamList = { TestScreen: { randomString: string } TestScreen2: { randomString2: string } } type TestScreenStackProps = StackScreenProps<TestScreenParamList, 'TestScreen' | 'TestScreen2'> const TestScreen = ({ route, navigation }: TestScreenStackProps) => { // 用in操作符做类型守卫,判断参数类型 if ('randomString' in route.params) { console.log(route.params.randomString) // 这里TS明确知道是TestScreen的参数 } else { console.log(route.params.randomString2) // 这里TS明确知道是TestScreen2的参数 } return <></> }
为什么会报错?
当你使用联合屏幕名称时,route.params的类型会变成{ randomString: string } | { randomString2: string }。TypeScript的类型系统会严格检查:因为联合类型的成员可能没有某个属性(比如randomString在TestScreen2的参数里不存在),所以直接访问会触发错误,必须通过类型判断来收窄类型范围。
内容的提问来源于stack exchange,提问作者Harrison
相关产品推荐
相关产品推荐

