reactjs - TypeScript 条件类型 : Extract component props type from react component

标签 reactjs typescript types conditional-types

使用 TypeScript 2.8 新的条件泛型类型功能,是否可以提取 TPropsReact.ComponentType<TProps>成分?我想要一种可以或者ComponentType 上工作的类型或 TProps本身,因此您可以 - 作为开发人员 - 通过两者之一:

例如:

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

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

最佳答案

有一个内置的助手

type AnyCompProps = React.ComponentProps<typeof AnyComp>

它也适用于原生 DOM 元素:

type DivProps = React.ComponentProps<"div">

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

关于reactjs - TypeScript 条件类型 : Extract component props type from react component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50084643/

相关文章:

css - 如何让输入单选元素在 React [material-ui] 中水平对齐?

jquery - 如何让 TypeScript 与 jQuery 插件配合使用?

json - 在 typescript 2.9.2 和 Angular 6 应用程序中导入 json 文件不起作用

vba - 限制类模块内集合中的类型

reactjs - npm 更新后 React 无状态组件损坏

swift - 苹果自己的 Swift 文档关于动态类型与编译时类型似乎是错误的

javascript - 有没有办法为 <Link> 提供条件?

javascript - React 组件投票向上和向下

reactjs - react : Show loading spinner while images load

reactjs - Typescript with React - 在通用组件类上使用 HOC