3

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!

1
  • Found out. It's intersection type :) Commented May 13, 2021 at 8:30

1 Answer 1

1

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'.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.