【问题标题】:TypeScript + React: Using one prop value to dynamically type anotherTypeScript + React:使用一个道具值动态键入另一个
【发布时间】:2020-08-10 03:40:29
【问题描述】:

我正在使用 TypeScript 编写一个 Link 组件,并试图实现一个支持我的应用程序路由使用的各种参数的类型化 API。

我有一些这样定义的路线:

enum Routes {
  CONTACT = '/contact'
  PRODUCT = '/product/[productId]'
}

type RouteParams = {
  [Routes.CONTACT]: undefined;
  [Routes.PRODUCT]: {
    productId: string
  }
}

Link 组件 API 是这样的:

type LinkProps = React.FC<{ href: Routes, params?: {} }>

我的问题是,这里的params 是否可以根据输入的href 值动态更改为RouteParams 中定义的正确类型?

例如:

<Link href={Routes.CONTACT} /> // correctly typed

<Link href={Routes.PRODUCT} params={{}} /> // error: missing 'productId' param

【问题讨论】:

  • 为什么不将参数定义为 [k: string]: string;
  • 感谢您的评论,这肯定是一个改进,但我认为它不能解决这里关于动态类型的问题。再次感谢!

标签: reactjs typescript


【解决方案1】:

这是我能做的最好的,但它是无铸型的并且类型检查出来:)

enum Routes {
  CONTACT = "/contact",
  PRODUCT = "/product/[productId]",
}

type RouteParams = {
  [Routes.CONTACT]: {};
  [Routes.PRODUCT]: {
    productId: string;
  };
};

function TLink<T extends Routes>({ href, ...p }: { href: T } & RouteParams[T]) {
  return <Link href={href} {...p} />;
}

function Component() {
  return (
    <Container>
      <TLink href={Routes.CONTACT} />
      <TLink href={Routes.PRODUCT} productId="42" />
    </Container>
  );
}

【讨论】:

  • 非常感谢!您的解决方案正是我想要的。我已经更新了您提供的链接组件示例的类型,如下所示:``` const Link = ({ href, ...p }: { href: T } & { params?: RouteParams[T ] }) => ; ``` 实现我想要的在指定道具中传递参数的API。再次感谢!
猜你喜欢
  • 2022-06-11
  • 1970-01-01
  • 1970-01-01
  • 2020-08-18
  • 2023-01-10
  • 1970-01-01
  • 1970-01-01
  • 2019-05-10
  • 2020-07-23
相关资源
最近更新 更多