Reputation: 51
Just want to a question about React.ComponentProps itself.
Still learning the syntax, do you guys know the meaning of this code below
type Props = React.ComponentProps<typeof ComponmentA> & {
someProp: string;
};
Thanks!
Upvotes: 3
Views: 66
Reputation: 11852
Let's break this down.
First typeof
- typeof infers a type from a constant.
So for example
const foo = {
a: "hello",
b: 999
};
type TypeofFoo = typeof foo;
//type TypeofFoo = {
// a: string;
// b: number;
//}
So for typeof a React component:
const MyComponent = (props: {
name: string
}) => {
const {name} = props;
return <div>{name}</div>
}
type TypeofMyComponent = typeof MyComponent;
//type TypeofMyComponent = (props: {
// name: string;
//}) => JSX.Element
We can see the the typeof a React component in this case is just a function with a particular signature and returns a JSX.Element.
Second React.ComponentProps
- appears to just extract the props of a React component. So:
type ComponentPropsOfTypeofMyComponent = ComponentProps<TypeofMyComponent>;
//type ComponentPropsOfTypeofMyComponent = {
// name: string;
//}
Thirdly the &
syntax is just creating a type intersection
So for example:
type A = {
name: string;
}
type B = {
age: number;
}
type C = A & B;
// type C = {
// name: string;
// age: number;
// }
Long story short - what that code is doing is saying 'Hey whatever the shape of the props of ComponentA is - and add {someProps: string;}
to it'.
Upvotes: 1