如何在TypeScript中为expo-router的Link组件使用动态路由?
修复expo-router Link组件与自定义路由类型的TypeScript兼容问题
方案一:让自定义路由类型继承expo-router的StaticRoutes(推荐)
直接基于expo-router自动生成的StaticRoutes类型定义你的ItemPath,TypeScript会自动识别它是合法路由类型,无需额外断言:
import { StaticRoutes } from 'expo-router'; // 基于框架生成的静态路由类型定义子集 type ItemPath = StaticRoutes['/item/one'] | StaticRoutes['/item/two'] | StaticRoutes['/item/three']; type Item = { label: string; path: ItemPath; }; // 组件代码保持不变 import { Link } from 'expo-router'; const items: Item[] = [ {label: 'one', path: '/item/one'}, {label: 'two', path: '/item/two'}, {label: 'three', path: '/item/three'} ]; export default function Page() { return ( <View> {items.map(item => ( <Link href={item.path} key={item.label}> {item.label} </Link> ))} </View> ); }
方案二:正确导入RelativePathString并进行类型断言
如果坚持使用自定义ItemPath类型,可以从expo-router中正确导入RelativePathString类型,再对路径做类型断言:
import { Link, RelativePathString } from 'expo-router'; // 自定义类型保持不变 type ItemPath = "/item/one" | "/item/two" | "/item/three"; type Item = { label: string; path: ItemPath; }; const items: Item[] = [ {label: 'one', path: '/item/one'}, {label: 'two', path: '/item/two'}, {label: 'three', path: '/item/three'} ]; export default function Page() { return ( <View> {items.map(item => ( <Link href={item.path as RelativePathString} key={item.label}> {item.label} </Link> ))} </View> ); }
问题原因
expo-router的Link组件href属性接受的类型是StaticRoutes | RelativePathString | http${string}``,其中StaticRoutes是框架根据项目路由自动生成的类型集合。你自定义的ItemPath虽然字面量与合法路由一致,但TypeScript不会自动将其视为StaticRoutes的子集——只有当自定义类型明确基于StaticRoutes定义,或通过断言匹配到允许的类型时,才能通过类型检查。
内容的提问来源于stack exchange,提问作者Lau
相关产品推荐
相关产品推荐

