1

What is the "&" sign in a class definition?

In my class I found out that I need the following class definition:

class myList extends Component<RouteComponentProps<any> & IMyList> {

I find many other examples with comma instead of &, but with comma I get the error:

prop x does not exist

5
  • 1
    stackoverflow.com/questions/33875609/typescript-operator Commented Apr 23, 2019 at 10:37
  • instead of using an intersection type you should probably let IMyList extend RouteComponentProps<any> Commented Apr 23, 2019 at 10:41
  • 1
    @Thomas Not necessarily, either way will work for component props. & means intersection ie the props will be RouteComponentProps<any> and IMyList. Putting a , mean you are passing the other type parameter (for state) and thus props will be RouteComponentProps<any> and state will be IMyList Commented Apr 23, 2019 at 10:56
  • 1
    @TitianCernicova-Dragomir I know that both ways will work. It just seems to me that the OP is very inexperienced. And although I'm confident that he will soon understand these types, I think that it is way easier for an inexperienced programmer to create a big mess and repeat yourself all over the place with this construct. That's why I recommend to use inheritance instead. Commented Apr 23, 2019 at 11:06
  • @Thomas Yes, from that point of view I agree, inheritance may be easier to grasp Commented Apr 23, 2019 at 11:07

1 Answer 1

4

The & operator is called Intersection Type

It allows you to

...take two objects and create a new one that has the features of both these objects.

Think about it as "a type which is both typeA and typeB". I.E. a new type with properties from each object in the intersection type declaration.

P.S. I strongly suggest you to read the book in the link. It was very helpful for me.

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.