【问题标题】:TypeScript conditional types: Extract component props type from react componentTypeScript 条件类型:从反应组件中提取组件道具类型
【发布时间】:2018-10-09 14:41:27
【问题描述】:

使用 TypeScript 2.8 新的条件泛型类型功能,是否可以提取 React.ComponentType<TProps> 组件的 TProps?我想要一种可以要么ComponentTypeTProps 本身上工作的类型,因此您可以 - 作为开发人员 - 通过两者中的任何一个:

例如:

interface TestProps {
    foo: string;
}

const TestComponent extends React.Component<TestProps, {}> {
    render() { return null; }
}

// now I need to create a type using conditional types so that
// I can pass either the component or the props and always get the 
// TProps type back
type ExtractProps<TComponentOrTProps> = /* ?? how to do it? */

type a = ExtractProps<TestComponent> // type a should be TestProps
type b = ExtractProps<TestProps>     // type b should also be TestProps

这可能吗,有人可以提供解决方案吗?

【问题讨论】:

标签: reactjs typescript types conditional-types


【解决方案1】:

有一个内置的帮助器

type AnyCompProps = React.ComponentProps<typeof AnyComp>

它也适用于原生 DOM 元素:

type DivProps = React.ComponentProps<"div">

https://stackoverflow.com/a/55005902/82609

【讨论】:

  • 很高兴找到塞巴斯蒂安。
  • 就是这样。
【解决方案2】:

我建议使用React.ComponentType,因为它还会包含功能组件:

type ExtractProps<TComponentOrTProps> =
  TComponentOrTProps extends React.ComponentType<infer TProps>
    ? TProps
    : TComponentOrTProps;

【讨论】:

  • 现在将您的答案标记为正确的答案,因为我还支持 React 16.8 中引入的基于功能/挂钩的组件。
  • 如果 TComponentOrTProps 不是从 React.ComponentType 扩展而来,为什么要返回它?
【解决方案3】:

这是条件类型及其推理行为的非常直接的应用(使用 infer 关键字)

interface TestProps {
    foo: string;
}

class TestComponent extends React.Component<TestProps, {}> {
    render() { return null; }
}

type ExtractProps<TComponentOrTProps> = TComponentOrTProps extends React.Component<infer TProps, any> ? TProps : TComponentOrTProps;

type a = ExtractProps<TestComponent> // type a is TestProps
type b = ExtractProps<TestProps>     // type b is TestProps

【讨论】:

  • 这不再适用于 React 16.8 中引入的 React 功能组件(类型 React.FC
  • 如果 TComponentOrTProps 不是从 React.ComponentType 扩展而来,为什么要返回它?
  • @CristianE。我认为这是使ExtractProps&lt;TestProps&gt; 工作所必需的。如果ExtractProps 与 React.Component 一起使用,它将从它的声明中提取道具。否则ExtractProps 将假定TComponentOrTProps 只是一个Props 接口并按原样返回它
猜你喜欢
  • 2021-09-07
  • 1970-01-01
  • 1970-01-01
  • 2019-07-27
  • 2021-06-29
  • 2021-01-15
  • 1970-01-01
  • 1970-01-01
  • 2021-06-12
相关资源
最近更新 更多