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:
For example:
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 components use props to communicate with each other. Every parent component can pass some information to its child components by giving them props. Props might remind you of HTML attributes, but you can pass any JavaScript value through them, including objects, arrays, and functions.
Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and return HTML. Components come in two types, Class components and Function components, in this tutorial we will concentrate on Function components.
There's a built-in helper for that
type AnyCompProps = React.ComponentProps<typeof AnyComp>
And it also works for native DOM elements:
type DivProps = React.ComponentProps<"div">
https://stackoverflow.com/a/55005902/82609
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With