使用 TypeScript 2.8 新的条件泛型类型功能,是否可以提取 TProps
的 React.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">
关于reactjs - TypeScript 条件类型 : Extract component props type from react component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50084643/