我有一个项目列表,我可以点击这些项目来转到不同的页面.这些项存储在数组中.它们的形状如下:

type Item = {
  label: string
  path: ItemPath
}

type ItemPath = "/item/one" | "/item/two" | "/item/three"

其中ItemPath是类型I,声明了每个项目的所有可能路由.

然后,我try 使用Link组件,如下所示:

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>
  )
}

然而,href属性给了我一个打字错误:

类型‘ItemPath’不可赋值给类型‘StaticRoutes|RelativePathString|http${string}’.

我试过用<Link href={item.path as RelativePathString} />,但我找不到那种类型.我也花了一些时间寻找信息,但我找不到任何与我的问题相关的信息.

我希望TypeScrip能理解我的ItemPath类型是应用程序中所有路径的子集.

我该怎么解决这个问题?

推荐答案

解决了我在EXPO-路由链路组件中使用Href<T>的问题.

代码更改如下:

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 as Href<itemPath>} key={item.label}>
          {item.label}
        </Link>
       )}
    </View>
  )
}

这是link to the docs美元

Typescript相关问答推荐

TypeScript泛型参数抛出错误—?&#"' 39;预期"

基于键的值的打字动态类型;种类;

TypeScrip表示该类型不可赋值

角效用函数的类型推断

在实现自定义主题后,Angular 不会更新视图

表单嵌套太深

在Typescript 中,有没有`index=unfined的速记?未定义:某个数组[索引]`?

如何从扩展接口推断泛型?

为什么ESLint会抱怨函数调用返回的隐式`any`?

如何在ANGLE中注册自定义验证器

不带其他属性的精确函数返回类型

Typescript 类型守卫一个类泛型?

将对象的属性转换为正确类型和位置的函数参数

如何避免从引用<;字符串&>到引用<;字符串|未定义&>;的不安全赋值?

为什么受歧视的unions 在一种情况下运作良好,但在另一种非常类似的情况下却不起作用?

typescript如何从映射类型推断

TypeScript:如何使用泛型和子类型创建泛型默认函数?

记录的子类型<;字符串,X>;没有索引签名

如何使用 Angular 确定给定值是否与应用程序中特定单选按钮的值匹配?

错误:仅允许在‘使用服务器’文件中导出异步函数