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

SaschaM78
  • 4,376
  • 4
  • 33
  • 42
EirikO
  • 617
  • 8
  • 19
  • 1
    https://stackoverflow.com/questions/33875609/typescript-operator – Tholle Apr 23 '19 at 10:37
  • instead of using an [intersection type](https://www.typescriptlang.org/docs/handbook/advanced-types.html) you should probably let `IMyList` extend `RouteComponentProps` – Thomas Apr 23 '19 at 10:41
  • 1
    @Thomas Not necessarily, either way will work for component props. `&` means intersection ie the props will be `RouteComponentProps` and `IMyList`. Putting a `,` mean you are passing the other type parameter (for state) and thus props will be `RouteComponentProps` and state will be `IMyList` – Titian Cernicova-Dragomir Apr 23 '19 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. – Thomas Apr 23 '19 at 11:06
  • @Thomas Yes, from that point of view I agree, inheritance may be easier to grasp – Titian Cernicova-Dragomir Apr 23 '19 at 11:07

1 Answers1

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.

caruso_g
  • 404
  • 6
  • 16