TypeScript 条件类型:从 react 组件中提取组件 props 类型 [英] TypeScript conditional types: Extract component props type from react component

查看:123
本文介绍了TypeScript 条件类型:从 react 组件中提取组件 props 类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using TypeScript 2.8 new conditional generic type feature, is it possible to extract the TProps of a React.ComponentType<TProps> component? I want a type that can either work on the ComponentType or the TProps itself, so you can - as a developer - pass either of both:

例如:

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

这可能吗,谁能提供解决方案?

Is this possible, and can anybody provide a solution?

推荐答案

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

I'd suggest to use React.ComponentType, because it will also include functional components:

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

这篇关于TypeScript 条件类型:从 react 组件中提取组件 props 类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆